Transactional unit test over multiple datasources
Recently I needed to write an integration test that covered a transaction over multiple SessionFactories and different datasources. I wanted it to be an outside-the-container-test and therefor I needed some ability to do transactions over multiple datasources without all the stuff a J2EE container would provide.
A good start for writing transactional tests can be found, as usual, in Spring. All you need to do is to extend the AbstractTransactionSpringContextTests class and the rest is a piece of cake. Now the question is how to wire this up for multiple datasources?
To start we need some transaction manager and datasources that support XA transactions to use in my test. Thanks to my collegue Maarten Winkels I came across this excellent post on javaeye.com which gives an example on how to configure Spring, Hibernate and JOTM. JOTM is an open source transaction manager written in Java. Spring also provides support for using JOTM through the JotmFactoryBean.
Interestingly the class created by the JotmFactoryBean, the Jotm class, is used for exposing both the UserTransaction as the TransactionManager so regarding the transaction part we are done.
Now all we need is a XA compliant datasource. In both the Spring docs of the JotmFactoryBean and the post on javaeye.com the XAPool is used. Now to wire this all together in Spring xml you have to define something like this (assuming you need two datasources):
WEB-INF/hibernate-cfg-1.xml org.hibernate.cfg.AnnotationConfiguration org.hibernate.dialect.PostgreSQLDialect WEB-INF/hibernate-cfg-2.xml org.hibernate.cfg.AnnotationConfiguration org.hibernate.dialect.PostgreSQLDialect
And for the maven users, all dependencies are in the maven repository so just add the following dependencies to your pom and off you go!
jotm jotm 2.0.10 com.experlog xapool 1.5.0