Sunday, September 30, 2012

How to configure Hibernate 4 with JTA transaction for unit tests ?

Some time ago I had to configure Hibernate 4 to work with local unit tests with JTA. At the beginning I was a bit worried that it could be painful. But it appeared to be quite easy when I made it work. The big deal was to find out, how to configure hibernate to use JTA transaction manager (not thread local one), because it was hard to find any information, docs or manuals about this topic. So let's start with persistence.xml: Pay attention at transaction-type="JTA" setting. The other think is configuration when EntityManagerFactory is being build: So, the EntityManagerFactory has been build and configured. Now it's time to use it, in this purpose just call "emf.createEntityManager()" and You have ready to use EntityManager. And on the end crucial thing: How to menage transactions in unit test ? It's simple: So enjoy using JTA-like transactions in Your unit tests. Just remeber that this platform is mock implementation and You are not beyond full JEE server, so e.g. Injecting UserTransaction is not the best idea ;-)