1

I would like to understand when exactly commit happens and when exactly rollback happens in case of nested transaction with different isolation levels to calling and called methods,

For example, I have two spring services and i'm calling method2 of service2 from method1 of service1.

Method1 is having REQUIRED transaction scope and Method2 is having REQUIRES_NEW transaction scope as shown in the program below.

Service1 {

 @Transactional(propagation = Propagation.REQUIRED)
method1()
{
    for(int i=0; i<10; i++){
        service2.method2();
    }

    // Some more code which takes some time to process
}

}


Service2 {
 @Transactional(propagation = Propagation.REQUIRES_NEW)
 method2()
 {
    //Save some information to DB
    // Save an object using JPA
 }
}

Now my question is, As i understand REQUIRES_NEW will start a new transaction, But will it commit immediately on existing method2 or will the spring waits till method1 is completed and then commits?

I'm interested in at what point of time commit happens and row lock in DB gets released which is persisted in method2.

Note: Here i have placed both methods in different services so that spring can achieve nested transaction.

Thanks in Advance,

Vali

Rama
  • 13
  • 1
  • 6

1 Answers1

4

When you enter the method2 of service2, the transaction of the service1 (say tx1) get suspended, and a new transaction is created to service2 (say tx2). This new transaction is independent of the previous transaction, and will either commit or rollback independently.

tx2 will commit/rollback just when you return from the service2, and after that tx1 will resume from the point it suspended. The result of tx2 (whether it resulted in a commit or a rollback) will not affect the behavior of tx1.

Please read the Spring documentation. Check section 16.5.7 for more information about transaction propagation.

Community
  • 1
  • 1
  • Thanks for a quick reply. That's exactly my understanding as well. But what is happening with me is Rollbacks are working as expected and when it comes to commit though it is independent commit, looks like commit is happening only after method1 is completed.. – Rama Oct 15 '15 at 06:31
  • Are you using any ORM? if so what is the flush mode? Not sure if this the exact case. – Amila Banuka Amarasinghe Oct 15 '15 at 06:50
  • Thanks for the pointers Amila. After further analysis found that nested transactions are working as expected and the issue was in method1 there were some commits a table which is being modified in method2. As the same record is modified in two different transaction the sessions in DB were blocking. Now i have moved all the code to method which are dealing with same record and problem is solved. thanks for you support. – Rama Oct 16 '15 at 04:47