Transactional unit test over multiple datasources

31 Jul, 2007
Xebia Background Header Wave

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










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!



Have fun!


Get in touch with us to learn more about the subject and related solutions

Explore related posts