Milkmaid Milkmaid - 12 days ago 7
Java Question

EntityManager nested transaction atomicity

In legacy code I solving problem with nested transactions.
(Spring, CDI, etc cannot be used only 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 when I call inside method where is opened transaction another method with self transaction than it not behave atomic. Is there any solution how to achieve this without giving open entity manager as parameter?

Answer

JPA and JTA do not have support for nested transactions.

When you need an overall transaction management system. Than use one. There are many possibilites. Spring is one of it or a JavaEE container managed system in an application server. You can also handle the whole operation on your own with a JTA compliant transaction manager. I tell you as one who wrote a distributed transaction management system based on Jboss TM -> do not do it, it is not easy and it will cost a huge amount of time.