Announcement Announcement Module
No announcement yet.
Running JPA (Hibernate3) and JTA on IBM Websphere 6.1 & 7 Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Running JPA (Hibernate3) and JTA on IBM Websphere 6.1 & 7

    An old post of mine (Vincent Lussenburg), originally posted to a blog that is no longer online. I figured it has a nice place here on the springsource forum.


    At my current project, we’re currently working on the second release of a webapp that integrates with a couple of webservices. It features a N+1 architecture integrated by Spring 2.5.x. In this release, we have to persist into a single-consumer Oracle database. Since we have a tight deadline but do want to experiment with various ORM implementations in the future, we ended up deciding to use JPA1.0 with Hibernate3 as persistence provider.

    Purpose of this post

    The combination Websphere / Hibernate / JPA did provide some – shall we say.. challenges? You have some different approach routes to wire these technologies together and having a lot of choices can be confusing. The purpose of this post therefore is not only to show how we integrated it all but also why we did it this way. That hopefully helps others who are starting up a project with these technologies.

    And of course, some of the choices we made may be flawed. That’s the reason you can write comments below

    I created an example project with our setup, see the bottom of this post ([1]). Remember that nowadays you can download a development version of Websphere 7 at no charge at But you can also run this project in jetty ofcourse.

    Configuring JPA

    Setting up the PersistenceContext

    We decided to use Spring to bootstrap the JPA context. This is not the pure JEE way, I’ll get back to that in a later section. Spring’s LocalContainerEntityManagerFactoryBean does pretty much what the JEE container should do: bootstrap the JPA persistence context, but with the usual extra Spring flexibility.


    <!-- File has non-standard name to prevent WAS from processing it. We want Spring to process it (and avoid classpath hell on WAS). -->
    <persistence xmlns=""
    	<!-- Kept as light as possible in order to work with Spring in both J2SE and JEE. -->
    	<persistence-unit name="example-db">

    Spring application context

    <util:properties id="jpaProviderProperties" location="" />
    <bean id="entityManagerFactory"
    Non-standard filename so Websphere doesn't try to create the EM (and
    throw errors due to Hibernate not being on the AS classpath)
    <property name="persistenceXmlLocation" value="classpath:META-INF/persistence-spring.xml" />
    <property name="jpaProperties" ref="jpaProviderProperties" />
    The location of the persistence-spring.xml is important as it is used to find the Entities you want to persist (more info, see here). Ignore the for now, I’ll get to that in the section on integration tests.

    Transaction management
    Choosing a transaction manager

    In the end, we chose the most future-proof option: a JTA Transaction manager (TM). But we started out with these options:
    1. A (in JPA-speak) RESOURCE_LOCAL transaction manager. Spring provides the JpaTransactionManager. Cannot handle transactions for more than one XA resource (db, web service call, etc).
    1. A container-provided JTA transaction manager. Websphere provides the UOWManager and Spring providers a wrapper around it, offering full JTA support – transaction suspending, distributed transactions, the works. It can be created through the container-independent <tx:jta-transaction-manager /> in the spring context.
    1. What is all this transaction manager dogma? Do we need it? What’s wrong with using plain old autocommit?
    First: do we need a TM at all? Recent experiences at a different project showed that without a TM the use of connection pools is less efficient resulting in sizeable performance penalties, although it’s not completely clear why. So configuring a transaction manager seems the sensible thing to do. Since JTA is the default choice when running JPA in a JEE container and we had no good reason to reject this option, we went ahead with the default approach. Also, I have the feeling we might have to support WS-Transaction somewhere in the future (yes, YAGNI ).

    Transaction boundaries

    Next: how to configure the transaction boundaries. That’s pretty standard Spring-tx stuff (since we’re not using EJB3). We use Spring’s @Transactional annotations on the service layer (the transaction boundary in our application) and the rest is taken care of by Spring’s <tx:annotation-driven />. Works like a charm.

    Hibernate configuration

    Hibernate did give some problems with this setup. Since Spring is managing transactions, the only thing Hibernate should do is join the transaction. In order to do this Hibernate needs to look up the transaction manager. Sadly, neither the IBM UOWManager nor the Spring wrapper implements the TransactionManager interface. In the end, this configuration in did the trick:

    Bottom line: Hibernate is synchronizing to the transaction using a pre-WAS6.1 mechanism, and Spring is using the >=WAS6.1 way. Also, the Hibernate implementation has it’s problems: setRollbackOnly may be called in application code according to the spec, but this causes a nasty stacktrace in the log. But: it does work correctly. The whole story is explained in detail in this thread.

    On a sidenote: something confused me for a while: Hibernate3 configures itself based on the persistence.xml configuration. I noticed that it switched its transaction factory implementation automatically to ‘JoinableCMTTransactionFactory’. CMT is Container managed persistence, and we don’t use EJB2, since this seemed incorrect. After some time I read the javadoc here, and it turns out that this is in fact correct behaviour:

    The term ‘CMT’ is potentially misleading here; the pertinent point simply being that the transactions are being managed by something other than the Hibernate transaction mechanism.
    Opening the entity manager on each request

    We also added a filter (OpenEntityManagerInViewFilter) in the web.xml that sets up a EntityManager that the request starts en destroys it when the request ends (comparable with the OpenSessionInViewFilter for Hibernate).

    [1] example jpa-spring-hibernate-was project
    [2] You could also accomplish this by setting a on your classpath as Hibernate picks this up automatically, but this a more explicit way (but who cares about explicitness anymore in these times of @Autowired magic? :-)).
    Keywords: Websphere 6.1 7, JPA, EJB3 , JTA, Transaction management, Spring, Hibernate, Hibernate3
    Last edited by lussenvi; Jun 18th, 2011, 03:15 AM. Reason: typos

  • #2
    Running integration tests / Jetty

    Our data layer is isn’t unittested, it’s integration tested (as explained by yet another Vincent here). As a rule of thumb, we always try to keep the configuration as identical to the deployment configuration as possible. In this case, the JPA context is set up using the exact same application context file and persistence.xml. The only thing that’s different are the (in tests, I want Hibernate to use the H2 dialect and to automatically create the DB schema). They are read from the classpath (see sping XML snipplet at the beginning of this post): so you can have separate for your test (src/test/resources) and production (src/main/resources) environment [2].

    The resources normally provided by the JEE container (through JNDI) need to be mocked in test mode. This is a nice way to accomplish that:

    @ContextConfiguration(locations = { "classpath:spring-config-domain.xml" })
    @TransactionConfiguration(defaultRollback = true)
    public class UserDaoTest {
    	public static void beforeClass() throws Exception {
    		// Suppress the 'close', since we use a single connection in unittest
    		// anyways. The connection is terminated upon destruction in afterClass
    		singleConnectionDataSource = new SingleConnectionDataSource(
    				"jdbc:h2:mem:", true);
    		final TransactionAwareDataSourceProxy transactionAwareDataSourceProxy = new TransactionAwareDataSourceProxy(
    		contextBuilder = new SimpleNamingContextBuilder();
    				new JotmFactoryBean().getObject());
    	public static void afterClass() throws Exception {
    So, a datasource is registered in JNDI that keeps one connection open at all times (which is pretty handy when using a single threaded H2 DB) and a JOTM (jottum!) TM is used instead of the Websphere TM. The nice thing is the Spring configuration is identical, the <tx:jta-transaction-manager /> finds the JOTM TM now instead. Hibernate does need some manual configuration:

    Another bonus: if you want to run your app in a lite JEE container like Jetty for quick deployment, you can use pretty much the same config for that!

    Thanks for reading!

    Discussion – what about JPA by the JEE book?

    According to the EJB3 spec, the container should be in control of the PersistenceContext, roughly as follows:
    • Container detects META-INF/persistence.xml on webapp startup.
    • Container boots the JPA context based on the provided configuration.
    • Container sets the PersistenceContext on objects requiring it.
    • Container exposes the PersistenceContext via JNDI (as defined in the web.xml).
    Now try this on Websphere 7 (and 6.1 with the EJB3 feature pack, for that matter). As expected (remember: don’t feed the trolls), Websphere fails if you want to use your own persistence provider (in our case: Hibernate3). According to IBM this should be possible by setting the classloader to PARENT_LAST, but alas, that didn’t seem to work as documented. Messing with heavy weight containers like Websphere is tiresome: you have stop/start redeploy until you’ve gone cross-eyed. So, the pure JEE configuration for JPA in Websphere wasn’t convenient for us (which doesn’t say it’s impossible) and I personally don’t see that as a problem – because it’s just easier to do it the Spring way – which can be easily tested in an integration test, instead of deploy-time.
    Last edited by lussenvi; Jun 18th, 2011, 03:14 AM.