有时候在使用事务的时,做了事务嵌套,结果其中有一个抛出异常时,异常会一直连续跑出到最外层。
问题:明明捕获了异常为什么还会抛出。
@Transactional //第一层 会在方法执行完成后,在进行提交。此时代码已经失去了try-catch保护
public UserReply queryUser(UserQuery query)
{
BaseAccountExt user = null;
try
{
// 第二层。在此方法中也配置有事务,且抛出异常。它的异常会传递给当前方法
user = accountService.query(query.getAppCode());
}
catch(Exception ex) // 捕获异常
{
ex.printStackTrace();
}
System.out.println("-----------------------分割线-------------------------------");
return new UserReply(user);
}
@Transactional public BaseAccountExt query(String name){ // 先更新数据 BaseAccount baseAccountExt = new BaseAccount(); baseAccountExt.setFullName("abcd"); baseAccountExt.setName(baseAccountExt.getName()); baseAccountService.update(baseAccountExt); throw new RuntimeException("当前对象不为空!"); }
解决办法:网上可能有很多种说法,但是所有的方法都是一种规避.
- 或者去掉第一层Transactional,在该方法中,只有向下调用和DB交互,则此一层建议不要在追加事务。
- 让第二层嵌套事务,不要传递异常到外面,改变事务类型,(其实和第一种相似,但是可能会有业务限制)添加方法:propagation=Propagation.REQUIRES_NEW
- 在第一层外面,在做一层异常捕获,完整的保证事务异常绝对可以被拦截到。
@ExceptionHandler(value = { ApiException.class, BindException.class, Exception.class }) protected ApiReply checkedException(Exception ex) { ApiReply reply = new ApiReply(ApiReplyCode.FAILED); if (ex instanceof TransactionException) { reply = new ApiReply(ApiReplyCode.TRANSACTIONEXCEPTION); } logError(request, reply, ex); return reply; }
相关推荐
org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only at org.springframework.transaction.support....
Spring在Transaction事务传播行为种类,希望对大家有所帮助
spring-transaction.jar.zip
org.springframework.transaction-3.2.2.RELEASE最新版本
Spring交易演示spring-transaction-demo spring事务传播机制的7种使用方式
spring-tx spring-transaction spring事务管理实例
分布式事务框架LCN支持springcloud 2.0.5 ,transaction-springcloud-4.1.2.jar
测试spring事务管理 搭建了ssh框架的web工程 本工程用到的数据库表很简单 user(id, name) 可自行创建 本例所有的事务放在service层进行管理,方法中间抛出运行时异常以测试是否回滚 Spring配置文件中关于事务...
Spring中的事务管理问题:org.springframework.transaction-3.1.0.M1.jar包。org.springframework.transaction-3.1.0.M1.jar包。
org.springframework.transaction-3.0.0.M4.jar
Spring+iBatis+JOTM实现JTA事务: 如何处理跨库事物:spring + jtom 的jta事务是个很好的选择. 这个源码示例非常不错,包括所有的源码和jar包,下载后eclipse 或 myeclipse 导入就能用。 里面有详细的说明和注释,...
org.springframework.transaction-3.1.0.M2
spring-hibernate-maven-transaction整合
spring 事务管理工程,导入到MyEclipse 中既可以使用
Could not roll back Hibernate transaction.doc
里面为一个演示spring事务传播机制的小demo。简单实现转账功能,通过添加注解调整传播级别,同时通过日志打印查看sql是否执行,在mysql中的数据是否发生了变化(操作提交还是回滚了)。
org.springframework.transaction-3.1.0.M1.jar
org.springframework.transaction-3.2.4.RELEASE.jar,最新版的org.springframework.transaction,Wed Aug 07 16:44:37 GMT+01:00 2013
「工控安全」asec-w04-derived-unique-token-per-transaction - APT 数据泄露 工控安全 勒索软件 大数据 APT攻击
org.springframework.transaction-sources-3.0.1.RELEASE-A.jar 免费下载 org.springframework.transaction-sources-3.0.1.RELEASE-A.jar 源码,免费下载 如果不能免费下载,关注我,评论区联系我索要!