wangzhenhui1991 / Notes

3 stars 0 forks source link

spring @Transactional try catch问题 #28

Open wangzhenhui1991 opened 7 years ago

wangzhenhui1991 commented 7 years ago

stackOverFlow

在spring中使用@Transactional注解时,如果在方法中使用了try{...}catch(){...},将无法触发transactional的rollback. 例如:

class A{

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

        }
        return res ;
    }
}

解决方法:

1.推荐方案:使用注解标记Exception

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

2.使用TransactionAspectSupport

@Transactional
public Result doStuff(){
  try {
    // business logic...
  } catch (Exception ex) {
    // trigger rollback programmatically
    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
  }
}
wangzhenhui1991 commented 7 years ago

上述两种方法中,目前成功通过测试,并且通过在执行过程中添加int a = 1/0;引发异常测试,方法二成功回滚。

@Transactional
public Result doStuff(){
  try {
    // business logic...
    int a = 1/0;
  } catch (Exception ex) {
    // trigger rollback programmatically
    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

  }
}