Home > database >  Transaction propagation in spring @required
Transaction propagation in spring @required

Time:09-08

@GetMapping("trans")
    @Transactional()
    public String primaryTrans() {
        User u1 = new User(0,"test","[email protected]");
        us.save(u1);
        User u2 = new User(0,"test1","[email protected]");
        us.save(u2);
        secondaryTrans();
        return "index";
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    private void secondaryTrans() {
        // TODO Auto-generated method stub
        User u2 = new User(0,"test2","[email protected]".repeat(300));
        us.save(u2);
    }

Here i am manually raising DATA TOO LONG exception from secondary transaction, But it causes primary transaction also rolled back. How can we make sure that primary transaction to be committed irrespective of secondary transaction

CodePudding user response:

In this case, since the second method is called from the same class, the second transaction is most likely not created. Springs transactional support uses AOP proxies to create transactions. The docs contain a description on why this will not work.

CodePudding user response:

The simplest way is to catch the exception thrown from secondaryTrans() method, so just wrap secondaryTrans() into try-catch block:

try {
  secondaryTrans();
} catch (Exception e) {
  //...
}
  • Related