pringMVC事务回滚

2018-11-17  本文已影响0人  嘻洋洋

事务回滚机制

//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();       
     }        
}
上一篇 下一篇

猜你喜欢

热点阅读