Spring @Transactional annotation when using try catch block

for example

class A{
    
    @Transactional
    public Result doStuff(){
        Result res = null;
        try {
          // do stuff 
        } catch (Exception e) {
            
        }
        return res ;
    }
}

If there is an exception in the method doStuff the transaction isn’t rolled back.

To rollback the exception programmatically, we can do something like below.

declarative approach

@Transactional(rollbackFor={MyException1.class, MyException2.class, ....})
public Result doStuff(){
   ...
}

programmatic rollback

you need to call it from TransactionAspectSupport.

    public Result doStuff(){
      try {
        // business logic...
      } catch (Exception ex) {
        // trigger rollback programmatically
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      }
    }

You are strongly encouraged to use the declarative approach to rollback if at all possible.
Programmatic rollback is available should only be used if you absolutely need it.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)