title: How to rollback transaction in JPA?
body: <p>I have an <code>EntityManager</code> object maintained by the Spring framework and I inject it in whatever DAO class I want using the <code>@PersistenceContext</code> annotation like this..</p>
  
  <pre><code>@PersistenceContext(unitName="entityManager")
  private EntityManager em;
  </code></pre>
  
  <p>I use those DAO classes to save in the database something like this..</p>
  
  <pre><code>class MyClass
  {
      @Resource(name="myDao")
      private MyDao dao;
  
      @Resource(name="myAnotherDao")
      private MyAnotherDao anotherDao;
  
      public void save(String s1,String s2)
      {
          try
          {
               MyEntity m=new MyEntity();
               m.setName(s1);
               // .. and so on ..
  
               XYZ x=new XYZ();
               x.setDEF(s2);
  
               anotherDao.save(x);
  
               m.setXYZ(x);
               // .. some other stuff .. //
               dao.saveEntity(m);
           }
           catch(Exception e)
           {
               // I would like to rollback the transaction
           }
       }
  }
  </code></pre>
  
  <p>Now, both the daos here use the same <code>EntityManager</code> injected through <code>@PersistenceContext(unitName="entityManager")</code>. Now, if an exception occurs after <code>setXYZ()</code>, then I would like to rollback even the saved <code>XYZ</code> entity. But, how do I get the <code>EntityManager</code> from that?</p>
  
  <p>If all the daos hold the same object, then can I just call the <code>getTransaction().rollback()</code> method of the <code>EntityManager</code> class? Does the <code>getTransaction()</code> return a new transaction or any transaction that is currently associated with <code>EntityManager</code>?</p>