Wednesday, February 18, 2009

Testing JPA with Spring's AbstractTransactionalJUnit4SpringContextTests

Today I had to solve an interesting problem. Searching the web for quite some time didn't solve my problem so I thought I would explain how I solved it.

We are using Spring's AbstractTransactionalJUnit4SpringContextTests to test persistence for most of our test cases using JPA. This works nicely for the most part and there are many references on how to do this on the web. The key features are that by extending this class it gives you the spring context and you can use an EntityManager. Another feature is that it will rollback after the test completes (at least it's supposed to). This is working properly for most of our tests.

The problem occurred when some tests were not rolling back properly. It was leaving some data in the database after the test ran. Of course this shows up when you run another test and the data collides. I was also puzzled when some of the objects were rolled back and others were not in the same test case.

We narrowed it down to the fact that entity being tested used @TableGenerator and @GeneratedValue(strategy = GenerationType.TABLE ...) JPA annotations and the other entities were not. So something about this way of generating id values was throwing the tests into a funky state that causes partial rollbacks. I don't know exactly what was going on under the covers but I did find a solution.

By telling the Spring test not to rollback by using @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false) and then removing the test data in a cleanup method annotated with @After did the trick.

I wish I had more time to understand why I needed to do this work-around but like usual I have to move on to the next task. If anyone out there understands why this is happening please post a comment. I hope this blog will save someone else an afternoon of debuging!

4 comments:

  1. Jack, Your mom says that this problem is way over her head.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. I had a lot of issues caused by this problem. It seems like this is fixed in the curren Spring 3.0.0 milestone builds

    It all seems to be related with this bug:
    http://jira.springsource.org/browse/SPR-5315

    ReplyDelete
  4. Thanks Alan for the comment. It turns out that I just Friday got to the bottom of the issue. It seems that there is an issue with the “Table” strategy in hibernate. I’ve posted a message on the hibernate forums to see if I can get some help. https://forum.hibernate.org/viewtopic.php?f=1&t=997563

    ReplyDelete