blog.smart-java.nl
Ordina J-Technologies – Java Blog

Welcome

Welcome to the Ordina J-Technologies Java[tm] Blog.



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

By: Vincent Lussenburg, 5 May 2010

Background

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 (pretty much like the J-Technologies reference 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 IBM.com. 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.

persistence-spring.xml

	

org.hibernate.ejb.HibernatePersistence
		java:comp/env/jdbc/testDb
	

Spring application context
<util:properties id="jpaProviderProperties" location="classpath:jpaVendor.properties" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!--
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" />

</bean>

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 jpaVendor.properties 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).
  2. 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.
  3. 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 jpaVendor.properties did the trick:

hibernate.transaction.manager_lookup_class=org.hibernate.transaction.WebSphereExtendedJTATransactionLookup

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).

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 jpaVendor.properties (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 jpaVendor.properties 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:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring-config-domain.xml" })
@TransactionConfiguration(defaultRollback = true)
public class UserDaoTest {
[...]
	@BeforeClass
	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);
		singleConnectionDataSource.setDriverClassName("org.h2.Driver");
		final TransactionAwareDataSourceProxy transactionAwareDataSourceProxy = new TransactionAwareDataSourceProxy(
				singleConnectionDataSource);

		contextBuilder = new SimpleNamingContextBuilder();
		contextBuilder.bind("java:comp/TransactionManager",
				new JotmFactoryBean().getObject());
		contextBuilder.bind("java:comp/env/jdbc/testDb",
				transactionAwareDataSourceProxy);
		contextBuilder.activate();
	}

	@AfterClass
	public static void afterClass() throws Exception {
		contextBuilder.deactivate();
		singleConnectionDataSource.destroy();
	}
[...]
}

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:

hibernate.transaction.manager_lookup_class=org.hibernate.transaction.JOTMTransactionManagerLookup

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!

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.

Final words

So, is this the best solution? THE way of configuring JPA/JTA/Hibernate/WAS? Of course not. The is no right answer here I think, it all depends on the environment you’re in. But by explaining why this seems to be a nice fit for our situation, I hope to help those we need to use these technologies but can’t seem to see the forest for the trees.

Thanks for reading!

Links

[1] example jpa-spring-hibernate-was project
[2] You could also accomplish this by setting a hibernate.properties 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



[ 2 comments ] - [ Add a comment ]



Reflection slow? Class vs. Constructor newInstance

By: Jan-Kees van Andel, 1 May 2010

My last article triggered a lot of responses of people, which I, of course, try to answer.
One question, by Tofarr, was:

You are not caching the contructor! class.newInstance() internally looks for the no arg constructor each time – I would be curious to see how doing a Constructor c = class.getConstructor() would affect the timing…

This [...]

[Read more...]



[ 4 comments ] - [ Add a comment ]



Reflection slow? Well, it depends…

By: Jan-Kees van Andel, 25 April 2010

In this article, I’ll show you some ways to turn slow reflective code into faster code.
Reasons to use reflection
As some of you may know, many frameworks and libraries use reflection to do their thing. Reflection can be a solution for many sorts of issues, like:

Configuration. Many frameworks use text-based configuration, like XML. Classes are often [...]

[Read more...]



[ 14 comments ] - [ Add a comment ]



Immutable lists

By: Pieter van der Meer, 26 March 2010

The last couple of years there is more and more talk about concurrency. One of the main issues is the access data from the various threads that you have running.
Brian Goetz has a simple statement on how to solve this:  Use immutable objects where ever possible. Although true it is not always as simple to [...]

[Read more...]



[ 4 comments ] - [ Add a comment ]



JSF 2.0 ClientBehavior: First impressions

By: Jan-Kees van Andel, 19 March 2010

In my previous article, I wrote about my first real JSF 2.0 ClientBehavior, called ValidateBeanBehavior.
While programming, I’ve experienced some issues that, in my opinion, make the ClientBehavior less usable in many cases.
Events
A ClientBehavior is attached to a component, both on the server side and on the client side. On the client side, this simply means [...]

[Read more...]



[ No comments ] - [ Add a comment ]



Older posts


  • JSF 2.0 ClientBehavior: Bean Validation in JavaScript (17 March 2010, by Jan-Kees van Andel)
  • How to de-frameset a Web App with Apache Tiles 2 (16 March 2010, by Assen Kolov)
  • Unit Testing a Bean Validation ConstraintValidator (12 March 2010, by Jan-Kees van Andel)
  • Hibernate, lazy loading and inheritance (8 March 2010, by gnoij)
  • Using Unified Expression Language in Maven-Jetty-Plugin (27 February 2010, by Jan-Kees van Andel)
  • REST made easy with Java EE 6 and JAX-RS 1.1 (19 February 2010, by Stephan Oudmaijer)
  • DefaultMessageListenerContainer troubles in Websphere (3 February 2010, by Michel.Schudel)
  • JSF 2.0: The most simple CDI integration use cases (31 January 2010, by Jan-Kees van Andel)
  • JSF 2.0: Maximum flexibility with System Events (24 January 2010, by Jan-Kees van Andel)
  • java.util.Calendar.getActualMaximum returns strange results (20 January 2010, by Peter Schuler)
  • Spring 3.0: REST services with Spring MVC (16 January 2010, by Stephan Oudmaijer)
  • Mockito (15 January 2010, by Sander Abbink)
  • JPA Optimisitic locking versus Pessimistic locking (14 January 2010, by Peter Schuler)
  • Spring Security 3.0 and CAS 3.3.4 integration (29 December 2009, by Stephan Oudmaijer)
  • A lot of exciting new stuff in december: Spring 3.0 & Java EE 6 (21 December 2009, by Stephan Oudmaijer)