架构师不得不知的Spring事务不能回滚的深层次原因


author: rocklei123
tags:

  • Java
  • Spring
  • Spring Transaction
    categories: Spring
    date: 2018-09-18 17:19:20

1.目标

  • 本文汇总了常见Spring事务无法回滚的问题,并配合实际案例模拟,并给出解决方案。通过本文可以更加详细的了解Spring事务无法回滚的原因。
  • 希望大家手动敲一遍代码,会收获颇丰。

2.测试环境信息

** 核心jar版本 **

spring-web-4.1.7.RELEASE.jar
spring-core-4.1.7.RELEASE.jar
spring-jdbc-4.1.7.RELEASE.jar
mybatis-spring-1.3.1.jar
mybatis-3.4.6.jar
ojdbc6-6.0.jar
junit-4.11.jar

3.try{}catch{非RuntimeException} 导致回滚失败

3.1 测试场景

模拟从中国农业银行(abcBank)张三账户转账给工商银行(icbcBank)李四账户200元。两个账户初始账户金额都为1000:

架构师不得不知的Spring事务不能回滚的深层次原因_第1张图片

3.2 测试代码

测试入口

@Test
public void testTransferAccountsFromZsABCBankToLsICBCBankRuntimeException() {
    System.out.println("test开始转账.........");
    int success = transferAccountsService.transferAccountRuntimeException("zhangsan", "lisi", 200);
    System.out.println("test转账业务完成  and success = " + success + ".........");
}

transferAccountsService (service层代码)

@Transactional
   public int transferAccountRuntimeException(String username1, String username2, double money) {
       int success = -1;
       try {
           System.out.println("transferAccountRuntimeException 开始转账业务------------------------");
           System.out.println("transferAccountRuntimeException 张三开始取钱------------------------");
           abcUserMoneyDao.drawMoney(username1, money);
           System.out.println("transferAccountRuntimeException 李四开始存钱------------------------");
           int a = 1 / 0;  //模拟出现异常
           icbcUserMoneyDao.saveMoney(username2, money);
           System.out.println("transferAccountRuntimeException 转账业完成务------------------------");
           success = 1;
       } catch (Exception e) {
           e.printStackTrace();
           success = 0;
       }
       return success;
   }

3.3 测试结果

张三取钱成功,李四存钱失败。钱转丢了!!!但是Spring事务并未回滚

架构师不得不知的Spring事务不能回滚的深层次原因_第2张图片

test开始转账.........
2018-09-19 10:58:15,998 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:248) org.springframework.beans.factory.support.DefaultListableBeanFactory
DEBUG: Returning cached instance of singleton bean 'txManager'
2018-09-19 10:58:15,999 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:248) org.springframework.beans.factory.support.DefaultListableBeanFactory
DEBUG: Returning cached instance of singleton bean 'transactionManager'
2018-09-19 10:58:16,079 org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:367) org.springframework.jdbc.datasource.DataSourceTransactionManager
DEBUG: Creating new transaction with name [com.rocklei123.spring.transaction.transferAccount.service.Impl.TransferAccountsServiceImpl.transferAccountRuntimeException]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2018-09-19 10:58:29,487 org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:206) org.springframework.jdbc.datasource.DataSourceTransactionManager
DEBUG: Acquired Connection [jdbc:oracle:thin:@127.0.0.1:1521:XE, UserName=APPROBE, Oracle JDBC driver] for JDBC transaction
2018-09-19 10:58:29,555 org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:223) org.springframework.jdbc.datasource.DataSourceTransactionManager
DEBUG: Switching JDBC Connection [jdbc:oracle:thin:@127.0.0.1:1521:XE, UserName=APPROBE, Oracle JDBC driver] to manual commit
transferAccountRuntimeException 开始转账业务------------------------
transferAccountRuntimeException 张三开始取钱------------------------
2018-09-19 10:58:29,642 org.mybatis.spring.SqlSessionUtils.getSqlSession(SqlSessionUtils.java:97) org.mybatis.spring.SqlSessionUtils
DEBUG: Creating a new SqlSession
2018-09-19 10:58:29,723 org.mybatis.spring.SqlSessionUtils.registerSessionHolder(SqlSessionUtils.java:128) org.mybatis.spring.SqlSessionUtils
DEBUG: Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4f1d60b0]
2018-09-19 10:58:30,802 org.mybatis.spring.transaction.SpringManagedTransaction.openConnection(SpringManagedTransaction.java:87) org.mybatis.spring.transaction.SpringManagedTransaction
DEBUG: JDBC Connection [jdbc:oracle:thin:@127.0.0.1:1521:XE, UserName=APPROBE, Oracle JDBC driver] will be managed by Spring
2018-09-19 10:58:30,855 org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159) com.rocklei123.spring.transaction.transferAccount.dao.ABCUserMoneyDao.drawMoney
DEBUG: ==>  Preparing: UPDATE ABC_USER SET money = money - 200.0 WHERE username = ?
java.lang.ArithmeticException: / by zero
	at com.rocklei123.spring.transaction.transferAccount.service.Impl.TransferAccountsServiceImpl.transferAccountRuntimeException(TransferAccountsServiceImpl.java:93)
  ...
	at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
	at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
	at com.sun.proxy.$Proxy21.transferAccountRuntimeException(Unknown Source)
	at tansferAccountTest.SpringTransactionTest.testTransferAccountsFromZsABCBankToLsICBCBankRuntimeException(SpringTransactionTest.java:62)
  ....
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
2018-09-19 10:58:32,027 org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159) com.rocklei123.spring.transaction.transferAccount.dao.ABCUserMoneyDao.drawMoney
DEBUG: ==> Parameters: zhangsan(String)
2018-09-19 10:58:32,039 org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159) com.rocklei123.spring.transaction.transferAccount.dao.ABCUserMoneyDao.drawMoney
DEBUG: <==    Updates: 1
2018-09-19 10:58:32,040 org.mybatis.spring.SqlSessionUtils.closeSqlSession(SqlSessionUtils.java:186) org.mybatis.spring.SqlSessionUtils
DEBUG: Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4f1d60b0]
transferAccountRuntimeException 李四开始存钱------------------------
2018-09-19 10:58:32,049 org.mybatis.spring.SqlSessionUtils$SqlSessionSynchronization.beforeCommit(SqlSessionUtils.java:284) org.mybatis.spring.SqlSessionUtils
DEBUG: Transaction synchronization committing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4f1d60b0]
2018-09-19 10:58:32,050 org.mybatis.spring.SqlSessionUtils$SqlSessionSynchronization.beforeCompletion(SqlSessionUtils.java:310) org.mybatis.spring.SqlSessionUtils
DEBUG: Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4f1d60b0]
2018-09-19 10:58:32,051 org.mybatis.spring.SqlSessionUtils$SqlSessionSynchronization.beforeCompletion(SqlSessionUtils.java:315) org.mybatis.spring.SqlSessionUtils
DEBUG: Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4f1d60b0]
2018-09-19 10:58:32,051 org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:755) org.springframework.jdbc.datasource.DataSourceTransactionManager
DEBUG: Initiating transaction commit
2018-09-19 10:58:32,052 org.springframework.jdbc.datasource.DataSourceTransactionManager.doCommit(DataSourceTransactionManager.java:269) org.springframework.jdbc.datasource.DataSourceTransactionManager
DEBUG: Committing JDBC transaction on Connection [jdbc:oracle:thin:@127.0.0.1:1521:XE, UserName=APPROBE, Oracle JDBC driver]
2018-09-19 10:58:32,059 org.springframework.jdbc.datasource.DataSourceTransactionManager.doCleanupAfterCompletion(DataSourceTransactionManager.java:327) org.springframework.jdbc.datasource.DataSourceTransactionManager
DEBUG: Releasing JDBC Connection [jdbc:oracle:thin:@127.0.0.1:1521:XE, UserName=APPROBE, Oracle JDBC driver] after transaction
2018-09-19 10:58:32,060 org.springframework.jdbc.datasource.DataSourceUtils.doReleaseConnection(DataSourceUtils.java:327) org.springframework.jdbc.datasource.DataSourceUtils
DEBUG: Returning JDBC Connection to DataSource
test转账业务完成  and success = 0.........

3.4 回滚失败原因

Spring的事务管理默认对Error异常和RuntimeException异常以及其子类进行事务回滚,且必须抛出异常,若使用try-catch对其异常捕获则不会进行回滚!(Error异常和RuntimeException异常抛出时不需要方法调用throws或try-catch语句);

以下是spring-tx-4.1.7.RELEASE.jar包中的部分源码:

package org.springframework.transaction.interceptor;

import org.springframework.transaction.TransactionDefinition;

public interface TransactionAttribute extends TransactionDefinition {
    String getQualifier();

    boolean rollbackOn(Throwable var1);
}

package org.springframework.transaction.interceptor;

import org.springframework.transaction.support.DefaultTransactionDefinition;

public class DefaultTransactionAttribute extends DefaultTransactionDefinition implements TransactionAttribute {
    private String qualifier;

    public boolean rollbackOn(Throwable ex) {
        return ex instanceof RuntimeException || ex instanceof Error;
    }
}

3.5 回滚失败解决办法

以下三种方式都可以解决try{}catch{非RuntimeException} 造成事务不回滚的问题
(1) throw new RuntimeException();

@Transactional
   public int transferAccountRuntimeException(String username1, String username2, double money) {
       int success = -1;
       try {
           System.out.println("transferAccountRuntimeException 开始转账业务------------------------");
           System.out.println("transferAccountRuntimeException 张三开始取钱------------------------");
           abcUserMoneyDao.drawMoney(username1, money);
           System.out.println("transferAccountRuntimeException 李四开始存钱------------------------");
           int a = 1 / 0;
           icbcUserMoneyDao.saveMoney(username2, money);
           System.out.println("transferAccountRuntimeException 转账业完成务------------------------");
           success = 1;
       } catch (Exception e) {
           e.printStackTrace();
           success = 0;
           throw new RuntimeException();
       }
       return success;
   }

(2)配置 rollbackFor = Exception.class

@Transactional(rollbackFor = Exception.class)
  public int transferAccountRuntimeException(String username1, String username2, double money) {
      int success = -1;
      try {
          System.out.println("transferAccountRuntimeException 开始转账业务------------------------");
          System.out.println("transferAccountRuntimeException 张三开始取钱------------------------");
          abcUserMoneyDao.drawMoney(username1, money);
          System.out.println("transferAccountRuntimeException 李四开始存钱------------------------");
          int a = 1 / 0;
          icbcUserMoneyDao.saveMoney(username2, money);
          System.out.println("transferAccountRuntimeException 转账业完成务------------------------");
          success = 1;
      } catch (Exception e) {
          e.printStackTrace();
          success = 0;
          throw e;
      }
      return success;
  }

(3)手动回滚事务

@Transactional
    public int transferAccountSetRollbackOnly(String username1, String username2, double money) {
        int success = -1;
        try {
            System.out.println("transferAccountRuntimeException 开始转账业务------------------------");
            System.out.println("transferAccountRuntimeException 张三开始取钱------------------------");
            abcUserMoneyDao.drawMoney(username1, money);
            System.out.println("transferAccountRuntimeException 李四开始存钱------------------------");
            int a = 1 / 0;
            icbcUserMoneyDao.saveMoney(username2, money);
            System.out.println("transferAccountRuntimeException 转账业完成务------------------------");
            success = 1;
        } catch (Exception e) {
            e.printStackTrace();
            success = 0;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return success;
    }

4.this调用导致回滚失败

4.1 测试场景

/**
  * @param username1
  * @param username2
  * @param money     业务需求:
  *                  1 transferAccountRequiresNew是一个加入事务的service层方法。且必须一个方法中同时调用 abcBankDrawMoney (zhangsan) 和  icbcUserMoneyDao.saveMoney(lisi)
  *                  2 abcBankDrawMoney (zhangsan)  允许失败,也就是说abcBankDrawMoney (zhangsan) 成功与否对icbcUserMoneyDao.saveMoney(lisi) 业务不影响
  *                  3 abcBankDrawMoney 是一个 @Transactional(propagation = Propagation.REQUIRES_NEW) 的方法 。该方法发生异常回滚
  *                  4 初始金额 abcBank  zhangsan 1000
  *                  4 初始金额 icbcBank  lisi  1000
  *                  

* 预期效果: * 1 、abcBankDrawMoney (zhangsan) 回滚 * 2 、icbcUserMoneyDao.saveMoney(lisi) 取钱成功 * 3、 预期金额 abcBank zhangsan 1000 * 4 、预期金额 icbcBank lisi 1200 *

* 真实结果: * 1、真实金额 abcBank zhangsan 800 * 2、真实金额 icbcBank lisi 1200 */

4.2 测试代码

@Test
public void testTransferAccountsFromZsABCBankToLsICBCBankRequiresNew() {
    System.out.println("test开始转账.........");
    transferAccountsService.transferAccountRequiresNew("zhangsan", "lisi", 200);
    System.out.println("test转账业务完成.........");
}

@Transactional
   public void transferAccountRequiresNew(String username1, String username2, double money) {
       try {
           this.abcBankDrawMoney(username1, money);
       } catch (Exception e) {
           e.printStackTrace();
       }
       System.out.println("准备开始为李四存钱业务---------------");
       icbcUserMoneyDao.saveMoney(username2, money);
       System.out.println("李四存钱成功---------------");
       System.out.println("转账业务完成---------------");
   }


   @Transactional(propagation = Propagation.REQUIRES_NEW)
   @Override
   public void abcBankDrawMoney(String username, double money) {
       System.out.println("准备开始为张三取钱业务---------------");
       abcUserMoneyDao.drawMoney(username, money);
       int a = 1 / 0;
       System.out.println(username + "张三取钱成功-------------");
   }



4.3 测试结果

我们看到即使abcBankDrawMoney 方法发生了异常,但是并未进行回滚操作,钱还是被取成功了,和我们之前预期的结果不是一样。

以下是执行结果:

架构师不得不知的Spring事务不能回滚的深层次原因_第3张图片

执行日志,并未回滚:

test开始转账.........
2018-09-19 14:26:06,230 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:248) org.springframework.beans.factory.support.DefaultListableBeanFactory
DEBUG: Returning cached instance of singleton bean 'txManager'
2018-09-19 14:26:06,231 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:248) org.springframework.beans.factory.support.DefaultListableBeanFactory
DEBUG: Returning cached instance of singleton bean 'transactionManager'
2018-09-19 14:26:06,376 org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:367) org.springframework.jdbc.datasource.DataSourceTransactionManager
DEBUG: Creating new transaction with name [com.rocklei123.spring.transaction.transferAccount.service.Impl.TransferAccountsServiceImpl.transferAccountRequiresNew]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2018-09-19 14:26:11,187 org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:206) org.springframework.jdbc.datasource.DataSourceTransactionManager
DEBUG: Acquired Connection [jdbc:oracle:thin:@127.0.0.1:1521:XE, UserName=APPROBE, Oracle JDBC driver] for JDBC transaction
2018-09-19 14:26:11,229 org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:223) org.springframework.jdbc.datasource.DataSourceTransactionManager
DEBUG: Switching JDBC Connection [jdbc:oracle:thin:@127.0.0.1:1521:XE, UserName=APPROBE, Oracle JDBC driver] to manual commit
准备开始为张三取钱业务---------------
2018-09-19 14:26:11,261 org.mybatis.spring.SqlSessionUtils.getSqlSession(SqlSessionUtils.java:97) org.mybatis.spring.SqlSessionUtils
DEBUG: Creating a new SqlSession
2018-09-19 14:26:11,344 org.mybatis.spring.SqlSessionUtils.registerSessionHolder(SqlSessionUtils.java:128) org.mybatis.spring.SqlSessionUtils
DEBUG: Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4db1f211]
2018-09-19 14:26:11,855 org.mybatis.spring.transaction.SpringManagedTransaction.openConnection(SpringManagedTransaction.java:87) org.mybatis.spring.transaction.SpringManagedTransaction
DEBUG: JDBC Connection [jdbc:oracle:thin:@127.0.0.1:1521:XE, UserName=APPROBE, Oracle JDBC driver] will be managed by Spring
2018-09-19 14:26:11,875 org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159) com.rocklei123.spring.transaction.transferAccount.dao.ABCUserMoneyDao.drawMoney
DEBUG: ==>  Preparing: UPDATE ABC_USER SET money = money - 200.0 WHERE username = ?
2018-09-19 14:26:12,292 org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159) com.rocklei123.spring.transaction.transferAccount.dao.ABCUserMoneyDao.drawMoney
DEBUG: ==> Parameters: zhangsan(String)
2018-09-19 14:26:12,477 org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159) com.rocklei123.spring.transaction.transferAccount.dao.ABCUserMoneyDao.drawMoney
DEBUG: <==    Updates: 1
2018-09-19 14:26:12,479 org.mybatis.spring.SqlSessionUtils.closeSqlSession(SqlSessionUtils.java:186) org.mybatis.spring.SqlSessionUtils

java.lang.ArithmeticException: / by zero
	at com.rocklei123.spring.transaction.transferAccount.service.Impl.TransferAccountsServiceImpl.ab
  .... 省略部分堆栈

	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
DEBUG: Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4db1f211]
准备开始为李四存钱业务---------------
2018-09-19 14:26:12,495 org.mybatis.spring.SqlSessionUtils.sessionHolder(SqlSessionUtils.java:163) org.mybatis.spring.SqlSessionUtils
DEBUG: Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4db1f211] from current transaction
2018-09-19 14:26:12,497 org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159) com.rocklei123.spring.transaction.transferAccount.dao.ICBCUserMoneyDao.saveMoney
DEBUG: ==>  Preparing: UPDATE ICBC_USER SET money = money + 200.0 WHERE username = ?
2018-09-19 14:26:12,499 org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159) com.rocklei123.spring.transaction.transferAccount.dao.ICBCUserMoneyDao.saveMoney
DEBUG: ==> Parameters: lisi(String)
2018-09-19 14:26:12,541 org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159) com.rocklei123.spring.transaction.transferAccount.dao.ICBCUserMoneyDao.saveMoney
DEBUG: <==    Updates: 1
2018-09-19 14:26:12,542 org.mybatis.spring.SqlSessionUtils.closeSqlSession(SqlSessionUtils.java:186) org.mybatis.spring.SqlSessionUtils
DEBUG: Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4db1f211]
李四存钱成功---------------
转账业务完成---------------
2018-09-19 14:26:12,544 org.mybatis.spring.SqlSessionUtils$SqlSessionSynchronization.beforeCommit(SqlSessionUtils.java:284) org.mybatis.spring.SqlSessionUtils
DEBUG: Transaction synchronization committing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4db1f211]
2018-09-19 14:26:12,545 org.mybatis.spring.SqlSessionUtils$SqlSessionSynchronization.beforeCompletion(SqlSessionUtils.java:310) org.mybatis.spring.SqlSessionUtils
DEBUG: Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4db1f211]
2018-09-19 14:26:12,546 org.mybatis.spring.SqlSessionUtils$SqlSessionSynchronization.beforeCompletion(SqlSessionUtils.java:315) org.mybatis.spring.SqlSessionUtils
DEBUG: Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4db1f211]
2018-09-19 14:26:12,546 org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:755) org.springframework.jdbc.datasource.DataSourceTransactionManager
DEBUG: Initiating transaction commit
2018-09-19 14:26:12,547 org.springframework.jdbc.datasource.DataSourceTransactionManager.doCommit(DataSourceTransactionManager.java:269) org.springframework.jdbc.datasource.DataSourceTransactionManager
DEBUG: Committing JDBC transaction on Connection [jdbc:oracle:thin:@127.0.0.1:1521:XE, UserName=APPROBE, Oracle JDBC driver]
2018-09-19 14:26:12,552 org.springframework.jdbc.datasource.DataSourceTransactionManager.doCleanupAfterCompletion(DataSourceTransactionManager.java:327) org.springframework.jdbc.datasource.DataSourceTransactionManager
DEBUG: Releasing JDBC Connection [jdbc:oracle:thin:@127.0.0.1:1521:XE, UserName=APPROBE, Oracle JDBC driver] after transaction
2018-09-19 14:26:12,553 org.springframework.jdbc.datasource.DataSourceUtils.doReleaseConnection(DataSourceUtils.java:327) org.springframework.jdbc.datasource.DataSourceUtils
DEBUG: Returning JDBC Connection to DataSource
test转账业务完成.........

4.4 回滚失败原因

在SpringIoC容器中返回的调用的对象是代理对象而不是真实的对象,只有被动态代理直接调用的才会产生事务。this调用并非代理对象。

4.5 回滚失败解决办法

通过AopContext.currentProxy(); 获取代理对象,通过代理对象调用abcBankDrawMoney()方法。

@Transactional
   public void transferAccountRequiresNew(String username1, String username2, double money) {
       try {
           TransferAccountsService proxy = (TransferAccountsService) AopContext.currentProxy();
           proxy.abcBankDrawMoney(username1, money);
       } catch (Exception e) {
           e.printStackTrace();
       }
       System.out.println("准备开始为李四存钱业务---------------");
       icbcUserMoneyDao.saveMoney(username2, money);
       System.out.println("李四存钱成功---------------");
       System.out.println("转账业务完成---------------");
   }

可能出现如下异常:

java.lang.IllegalStateException: Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.
	at org.springframework.aop.framework.AopContext.currentProxy(AopContext.java:64)
	at com.rocklei123.spring.transaction.transferAccount.service.Impl.TransferAccountsServiceImpl.transferAccountRequiresNew(TransferAccountsServiceImpl.java:62)

解决办法在spring 配置文件中设置

    <aop:aspectj-autoproxy expose-proxy="true"/>

小技巧:可以使用如下代码 确认你的bean 是代理对象吗?

AopUtils.isAopProxy()
AopUtils.isCglibProxy() //cglib
AopUtils.isJdkDynamicProxy() //jdk动态代理

5.其他原因导致回滚失败

  • mysql数据库且引擎是MyISAM造成的(因为不支持事务),改成InnoDB即可。

6.总结

本文总结了几种spring事务无法回滚的原因,总结如下:

  • try{}catch{} catch到非RuntimeException,并且未处理。默认spring仅对Error和RuntimeException 异常才回滚
  • this调用导致回滚失败。只有被动态代理直接调用的才会产生事务
  • mysql数据库且引擎是MyISAM造成的(因为不支持事务),改成InnoDB即可。

7.参考

http://jinnianshilongnian.iteye.com/blog/1850432

图灵学院张飞老师–《架构师不得不知道的Spring事物不能回滚的深层次原因-张飞》

8.欢迎持续关注

米宝窝 https://rocklei123.github.io/

你可能感兴趣的:(Spring)