title: Help with a reusable JPA transaction method w/ rollback
body: <p>I am retro-fitting transaction rollback support to a JPA-based java application, and am using Ecmel Ercans's approach to handling rollback (<a href="http://weblogs.java.net/blog/davidvc/archive/2007/04/jpa_and_rollbac.html" rel="nofollow noreferrer">http://weblogs.java.net/blog/davidvc/archive/2007/04/jpa_and_rollbac.html</a>) and JPA's kinks connected to rollbacks. It looks something like this:</p>
  
  <pre><code>EntityManager em = emf.createEntityManager();
  EntityTransaction tx = null;
  try {
  tx = em.getTransaction();
  tx.begin();
  ...
  ...
  tx.commit();
  } catch(Exception ex) {
    if(tx != null &amp;&amp; tx.isActive()) tx.rollback();
  } finally {
    em.close();
  }
  </code></pre>
  
  <p>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?</p>
  
  <p>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. </p>
  
  <p>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.</p>
  
  <p>Does anyone have a suggestion for a cleaner solution?</p>