Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 645
Milkmaid Avatar asked Sep 26 '26 04:09

Milkmaid


1 Answers

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.

like image 179
mh-dev Avatar answered Sep 28 '26 16:09

mh-dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!