Transaction propagation in spring @required

Viewed 22
@GetMapping("trans")
    @Transactional()
    public String primaryTrans() {
        User u1 = new User(0,"test","test@email.com");
        us.save(u1);
        User u2 = new User(0,"test1","test1@email.com");
        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","test3@email.com".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

2 Answers

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.

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