views:

691

answers:

1

I am retro-fitting transaction rollback support to a JPA-based java application, and am using Ecmel Ercans's approach to handling rollback (http://weblogs.java.net/blog/davidvc/archive/2007/04/jpa_and_rollbac.html) and JPA's kinks connected to rollbacks. It looks something like this:

EntityManager em = emf.createEntityManager();
EntityTransaction tx = null;
try {
tx = em.getTransaction();
tx.begin();
...
...
tx.commit();
} catch(Exception ex) {
  if(tx != null && tx.isActive()) tx.rollback();
} finally {
  em.close();
}

I have two questions regarding this. First, the thread where this solution comes up is two years old - has the problem with managed entities and rollbacks been fixed since?

If not,the problem is that the solution is a bit bulky and obscures what is actually beeing done. I'd like to make it a generic method that I can just call and plug whatever JPA actions I want into. I've been playing with it for a while with the idea that my generic method should take an instance of an anonymous class with a method of commands to do within the JPA transaction.

However, any solution I try with anonymous classes becomes almost as cumbersome as the initial problem. This is mainly because I need to have access to whatever entities I work with, either before or after the transaction-method call, as well as inside the anonymous class, usually all three. Plus the added overhead of moving data into an anonymous class which feels like a waste when done so "far down" into the code.

Does anyone have a suggestion for a cleaner solution?

+2  A: 

I would recommend using Spring's JPADaoSupport class, in combination with its @Transactional annotation support. This gives you a very clean way of demarcating your DAO methods with @Transactional in such a way as to specify how to handle exceptions, e.g. should a given exception trigger a rollback. It's also agnostic of the underlying persistence API, and so is consistent across JDBC, Hibernate, JPA, whatever.

It's highly declarative, and so your issue of too much clutter obscuring the business logic is greatly reduced.

skaffman