1.目标
- 本文汇总了常见Spring事务无法回滚的问题,并配合实际案例模拟,并给出解决方案。通过本文可以更加详细的了解Spring事务无法回滚的原因。
- 希望大家手动敲一遍代码,会收获颇丰。
2.测试环境信息
核心jar版本 1
2
3
4
5
6
7spring-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:
3.2 测试代码
测试入口1
2
3
4
5
6
public void testTransferAccountsFromZsABCBankToLsICBCBankRuntimeException() {
System.out.println("test开始转账.........");
int success = transferAccountsService.transferAccountRuntimeException("zhangsan", "lisi", 200);
System.out.println("test转账业务完成 and success = " + success + ".........");
}
transferAccountsService (service层代码)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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事务并未回滚
1 | test开始转账......... |
3.4 回滚失败原因
Spring的事务管理默认对Error异常和RuntimeException异常以及其子类进行事务回滚,且必须抛出异常,若使用try-catch对其异常捕获则不会进行回滚!(Error异常和RuntimeException异常抛出时不需要方法调用throws或try-catch语句);
以下是spring-tx-4.1.7.RELEASE.jar包中的部分源码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21package 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();1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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.class1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 (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)手动回滚事务1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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 测试场景
1 | /** |
4.2 测试代码
1 |
|
4.3 测试结果
我们看到即使abcBankDrawMoney 方法发生了异常,但是并未进行回滚操作,钱还是被取成功了,和我们之前预期的结果不是一样。
以下是执行结果:
执行日志,并未回滚:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60test开始转账.........
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()方法。1
2
3
4
5
6
7
8
9
10
11
12
13
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("转账业务完成---------------");
}
可能出现如下异常:1
2
3java.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 配置文件中设置1
<aop:aspectj-autoproxy expose-proxy="true"/>
小技巧:可以使用如下代码 确认你的bean 是代理对象吗?
1 | AopUtils.isAopProxy() |
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事物不能回滚的深层次原因-张飞》