Spring @Transactional annotation when using try catch block

前端 未结 4 1867
花落未央
花落未央 2020-12-13 13:46

If we catch the exception in method annotated with the @Transactional annotation, will it roll back if any exception occurs?

@Transactional(read         


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-13 14:27

    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.
    

提交回复
热议问题