关于Spring事务回滚的问题

http://blog.csdn.net/andyxuq/article/details/7982143

————————————————————————————————————————————————————————

在Spring的配置文件中,如果数据源的defaultAutoCommit设置为True了,那么方法中如果自己捕获了异常,事务是不会回滚的,如果没有自己捕获异常则事务会回滚,如下例
比如配置文件里有这么条记录:

<bean id="dataSource" class="xxx">
   <property name="xxx" value="xxx"/>
   <property name="xxx" value="xxx"/>
                     ....
     <property name="defaultAutoCommit" value="true" />
</bean>

 

那么现在有两个情况
情况1:如果没有在程序中手动捕获异常

@Transactional(rollbackFor = { Exception.class })
public void test() throws Exception {
     doDbStuff1();
     doDbStuff2();//假如这个操作数据库的方法会抛出异常,现在方法doDbStuff1()对数据库的操作   会回滚。
}

 

情况2:如果在程序中自己捕获了异常

@Transactional(rollbackFor = { Exception.class })
public void test() {
     try {
        doDbStuff1();
        doDbStuff2();//假如这个操作数据库的方法会抛出异常,现在方法doDbStuff1()对数据库的操作  不会回滚。
     } catch (Exception e) {
           e.printStackTrace();   
     }
}

 

现在如果我们需要手动捕获异常,并且也希望抛异常的时候能回滚肿么办呢?
下面这样写就好了,手动回滚事务:

@Transactional(rollbackFor = { Exception.class })
public void test() {
     try {
        doDbStuff1();
        doDbStuff2();
     } catch (Exception e) {
          e.printStackTrace();   
          TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//就是这一句了,加上之后,如果doDbStuff2()抛了异常,                                                                                       //doDbStuff1()是会回滚的
     }
}

原文地址:https://www.cnblogs.com/cuizhf/p/3554369.html