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!