美文网首页
pringMVC事务回滚

pringMVC事务回滚

作者: 嘻洋洋 | 来源:发表于2018-11-17 14:22 被阅读0次

事务回滚机制

  • 默认spring事务只在发生未被捕获的 runtimeexcetpion时才回滚。
  • 如果不写roolback-for,spring默认RuntimeException、UncheckedException及error才会回滚;
  • 如果异常被try{ }catch(){}了,事务就不会回滚了;如果要想让事务回滚,则必须在catch里面再往外抛异常try{ }catch(){throw newException}
    事务配置如下:
//name 是配的dao层的方法,roolback-for 需要回滚的异常名称
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true" />
            <tx:method name="query*" read-only="true" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="load*" read-only="true" />
            <tx:method name="select*" read-only="true" />
            <tx:method name="*" propagation="REQUIRED" rollback-for="Exception" />
        </tx:attributes>
    </tx:advice>

service层处理事务,那么service中的方法中不做异常捕获,或者在catch语句中最后增加throw new RuntimeException()语句,以便让aop捕获异常再去回滚

    public void update(TbSystemCodeD bean) throws Exception {
        getMapper().update(bean);
    }
    public void updateBySelective(TbSystemCodeD bean) throws Exception {
        getMapper().updateBySelective(bean);
    }   

spring aop 异常捕获原理

被拦截的方法需显式抛出异常,并不能经任何处理,这样aop代理才能捕获到方法的异常,才能进行回滚,默认情况下aop只捕获runtimeexception的异常,但可以通过 配置来捕获特定的异常并回滚 。
换句话说在service的方法中不使用try catch 或者在catch中最后加上throw new runtimeexcetpion(),这样程序异常时才能被aop捕获进而回滚。

//类似这样的方法不会回滚
if(userSave){        
    try {       
        userDao.save(user);        
        userCapabilityQuotaDao.save(capabilityQuota);       
     } catch (Exception e) {        
        logger.info("能力开通接口,开户异常,异常信息:"+e);       
     }       
 }
//下面的方法回滚(一个方法出错,另一个方法会回滚)
if(userSave){       
     try {        
        userDao.save(user);        
        userCapabilityQuotaDao.save(capabilityQuota);       
       } catch (Exception e) {       
        logger.info("能力开通接口,开户异常,异常信息:"+e);        
        throw new RuntimeException();       
     }        
}

相关文章

网友评论

      本文标题:pringMVC事务回滚

      本文链接:https://www.haomeiwen.com/subject/wqnbfqtx.html