Home > database >  JPA rollback nested Transaction
JPA rollback nested Transaction

Time:10-21

How to rollback nested transactions? let suppose if there is an exception in method5 then how to rollback method4 changes as well.

@Singleton
public class Case {
   @Inject
   CaseService caseService;
    
    @Transactional
    void method2(){
        var value = caseService.method4();
        caseService.method5(value);
    }
}

@Singleton
public class CaseService {
    @Transactional(Transactional.TxType.REQUIRES_NEW)
    public String method4(){
        return "some";
    }
    
    @Transactional(Transactional.TxType.REQUIRES_NEW)
    public void method5(String value){
    }
}

CodePudding user response:

If you want to rollback method4 call, then its statements should be within the same transaction as method5.

In the code that you provided method4 and method5 are always executed in separate transactions.

So, you could remove REQUIRES_NEW attribute.

CodePudding user response:

REQUIRES_NEW will always create a new transaction irrespective of any previous transaction. So, any rollback will happen only to that transaction. You want all of them (method4, method5) means method2 should be atomic. In that case, all of them should be under the same transaction which means you just have to use REQUIRED only or based on your use case start a new transaction on method2 and method4 and method5 should have REQUIRED.

If any of your transactional methods throws RuntimeException then they will be rolled back automatically. If you expect the rollback for checked exceptions also, then you would need to mention that in the annotation.

(rollbackFor=CustomException.class)

  • Related