Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When exactly does JPA REQUIRES_NEW transaction commit

In a spring container, with the code below:

public class A {

    @Transactional
    public void m1() {
        ...
        b.m2(); // call in a new transaction
        ...
    }

}

public class B {

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void m2() {
        ...
    }

}

when exactly the transaction created for m2() is committed? once m2() invocation ends, or once m1() invocation ends?

When does @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) commit? answers it for EJB, but it doesn't seem to be the same behavior for JPA.

I debugged it and I can only see the effect of m2() on DB after m1() ends, but that seems odd to me, am I missing something here?

UPDATE:

I was passing the entity I retrieved in m1() to m2() and updating it from there. So, actually merging the entity in m2() solves this and Mik378 answer is correct.

like image 623
Ahmad Y. Saleh Avatar asked Mar 12 '14 10:03

Ahmad Y. Saleh


1 Answers

From here:

Whether you're using the Spring Framework or EJB, use of the REQUIRES_NEW transaction attribute can have negative results and lead to corrupt and inconsistent data.
The REQUIRES_NEW transaction attribute always starts a new transaction when the method is started, whether or not an existing transaction is present.

REQUIRES_NEW starts a new transaction even if an existing transaction exist in the context.

So the short answer is: once m2() invocation ends

like image 109
Mik378 Avatar answered Sep 17 '22 12:09

Mik378