EntityManager nested transactional atomicity

In legacy code, I solve the problem with nested transactions. (Spring, CDI, etc. cannot only use pure JPA (EclipseLink))

em.getTransaction().begin();
em.persist(client);

em2.getTransaction().begin();
em2.persist(client1);            //saved into DB
em2.getTransaction().commit(); 

em.getTransaction().rollback();


public void method(){
    EntityManager em = entityManagerFactory.createEntityManager();
    em.getTransaction().begin();
    em.persist(client);

    nestedTransactionMethod();

    em.getTransaction().rollback();
}

public void nestedTransactionMethod(){
    EntityManager em = entityManagerFactory.createEntityManager();
    em.getTransaction().begin();
    em.persist(client);
    em.getTransaction().commit();
}

      

the problem is that I call inside a method where the transaction is open of another method with the transaction itself, than it does not behave atomically. Is there any solution how to achieve this without providing an open entity manager as a parameter?

+3


source to share


1 answer


JPA and JTA do not support nested transactions.



If you need a general transaction management system. Then use it. There are many possibilities. Spring is one of them or JavaEE Managed Container System in Application Server. You can also handle the entire transaction yourself using a JTA-compliant transaction manager. I tell you as someone who wrote a Jboss TM based distributed transaction management system -> don't do it, it's not easy and it will cost a huge amount of time.

+5


source







All Articles