@Transactional事务回滚异常:Transaction rolled back because it has been marked as rollback-only
问题描述
事务设置手动回滚:TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
代码需要返回比较友好的提示,但try…catch了,事务就不会回滚了,所以在catch中设置手动回滚,但每次执行完就抛出异常
2023-01-08 13:37:51.790 ERROR 5192 --- [nio-8880-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/ceshi] threw exception [Request processing failed; nested exception is org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only] with root cause
org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:870) ~[spring-tx-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:707) ~[spring-tx-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:633) ~[spring-tx-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:386) ~[spring-tx-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118) ~[spring-tx-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at cn.lw.service.impl.ShiwuServiceImpl$$EnhancerBySpringCGLIB$$33a86b07.insertRobllBack(<generated>) ~[classes/:na]
原因分析:
异常示例代码如下:
@Transactional
public String insertRobllBack(ForlanA forlanA, ForlanB forlanB) {
return forlanaService.insertForlanA(forlanA);
}
@Transactional
public String insertForlanA(ForlanA forlanA) {
try {
forlanBService.insertForlanB(new ForlanB());
} catch (Exception e) {
e.printStackTrace();
// 为了支持特定异常,设置手动回滚
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return "特定异常结果";
}
return "成功";
}
@Transactional
public void insertForlanB(ForlanB forlanB) {
forlanBDao.insert(forlanB);
int res = 1 / 0; //java.lang.ArithmeticException: / by zero
}
分析核心源码AbstractPlatformTransactionManager
@Override
public final void commit(TransactionStatus status) throws TransactionException {
if (status.isCompleted()) {
throw new IllegalTransactionStateException(
"Transaction is already completed - do not call commit or rollback more than once per transaction");
}
DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
if (defStatus.isLocalRollbackOnly()) {
if (defStatus.isDebug()) {
logger.debug("Transactional code has requested rollback");
}
processRollback(defStatus, false);
return;
}
if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
if (defStatus.isDebug()) {
logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
}
processRollback(defStatus, true);
return;
}
processCommit(defStatus);
}
private void processRollback(DefaultTransactionStatus status, boolean unexpected) {
try {
boolean unexpectedRollback = unexpected;
try {
triggerBeforeCompletion(status);
if (status.hasSavepoint()) {
if (status.isDebug()) {
logger.debug("Rolling back transaction to savepoint");
}
status.rollbackToHeldSavepoint();
}
else if (status.isNewTransaction()) {
if (status.isDebug()) {
logger.debug("Initiating transaction rollback");
}
doRollback(status);
}
else {
// Participating in larger transaction
if (status.hasTransaction()) {
if (status.isLocalRollbackOnly() || isGlobalRollbackOnParticipationFailure()) {
if (status.isDebug()) {
logger.debug("Participating transaction failed - marking existing transaction as rollback-only");
}
doSetRollbackOnly(status);
}
else {
if (status.isDebug()) {
logger.debug("Participating transaction failed - letting transaction originator decide on rollback");
}
}
}
else {
logger.debug("Should roll back transaction but cannot - no transaction available");
}
// Unexpected rollback only matters here if we're asked to fail early
if (!isFailEarlyOnGlobalRollbackOnly()) {
unexpectedRollback = false;
}
}
}
catch (RuntimeException | Error ex) {
triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
throw ex;
}
triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);
// Raise UnexpectedRollbackException if we had a global rollback-only marker
if (unexpectedRollback) {
throw new UnexpectedRollbackException(
"Transaction rolled back because it has been marked as rollback-only");
}
}
finally {
cleanupAfterCompletion(status);
}
}
通过源码,我们发现如果有全局回滚标记,还进行commit的情况下,则引发UnexpectedRollbackException
if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
if (defStatus.isDebug()) {
logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
}
processRollback(defStatus, true);
return;
}
// Raise UnexpectedRollbackException if we had a global rollback-only marker
if (unexpectedRollback) {
throw new UnexpectedRollbackException(
"Transaction rolled back because it has been marked as rollback-only");
}
If a participating transaction (e.g. with PROPAGATION_REQUIRED or PROPAGATION_SUPPORTS encountering an existing transaction) fails, the transaction will be globally marked as rollback-only
原因:就是我们内部事务已经抛出异常了,此时,事务已经被标记为rollback-only,最外层事务commit的话,这就有问题了
解决方案:
1、修改内层事务传播特性为@Transactional(propagation = Propagation.REQUIRES_NEW) ,这样内层和外层分别使用了不同事务,就不影响了
2、try…catch写到最外层事务,但是记得在catch设置手动回滚,不然还是存在上面问题
3、不要try…catch,异常直接抛到最外层
@Transactional事务回滚异常:Transaction rolled back because it has been marked as rollback-only的更多相关文章
- Spring中@Transactional事务回滚
转载: Spring中@Transactional事务回滚 一.使用场景举例 在了解@Transactional怎么用之前我们必须要先知道@Transactional有什么用.下面举个栗子:比如一个部 ...
- Spring @Transactional ——事务回滚
工作原理运行配置@Transactional注解的测试类的时候,具体会发生如下步骤1)事务开始时,通过AOP机制,生成一个代理connection对象,并将其放入DataSource实例的某个与Dat ...
- Spring中@Transactional事务回滚实例及源码
一.使用场景举例 在了解@Transactional怎么用之前我们必须要先知道@Transactional有什么用.下面举个栗子:比如一个部门里面有很多成员,这两者分别保存在部门表和成员表里面,在删除 ...
- Spring中@Transactional事务回滚(含实例详细讲解,附源码)
一.使用场景举例 在了解@Transactional怎么用之前我们必须要先知道@Transactional有什么用.下面举个栗子:比如一个部门里面有很多成员,这两者分别保存在部门表和成员表里面,在删除 ...
- Spring中@Transactional事务回滚(含实例具体解说,附源代码)
一.使用场景举例 在了解@Transactional怎么用之前我们必须要先知道@Transactional有什么用. 以下举个栗子:比方一个部门里面有非常多成员,这两者分别保存在部门表和成员表里面,在 ...
- Spring事务回滚和异常类
1.异常的一些基本知识 异常的架构 异常的继承结构:Throwable为基类,Error和Exception继承Throwable.Error和RuntimeException及其子类成为未检查异常( ...
- @Transactional 的回滚
默认情况下,Exception是不会引起回滚操作的,RuntimeException才会引起回滚操作. 当然如果所有的Exception都要回滚的话,直接@Transactional(rollback ...
- Try-Catch包裹的代码异常后,竟然导致了产线事务回滚!
导读:一段被try-catch包裹后的代码在产线稳定运行了200天后忽然发生了异常,而这个异常竟然导致了产线事务回滚.这期间究竟发生了什么?日常在项目过程中该如何避免事务异常?就在这个时候,老板拿着 ...
- (转)spring异常抛出触发事务回滚策略
背景:在面试时候问到事务方法在调用过程中出现异常,是否会传递的问题,平时接触的比较少,有些懵逼. spring异常抛出触发事务回滚策略 Spring.EJB的声明式事务默认情况下都是在抛出unchec ...
- spring @Transaction事务回滚失败
今天客户提出一个新问题,出库一批商品,提示失败了,但是库存数量却减少了.看了一下代码一头雾水,我们的代码加了事物,且捕获异常. 经过调试代码发现就是两个原因导致的 第一.在当前方法的catch中处理了 ...
随机推荐
- 浅尝 ECDHE 协议流程
前言 ECDHE 我之前是听都没听过, 但是新业务需要对前后端通信进行加密, 经过大佬推荐才知道有这个东西, 经过几天的学习和踩坑, 才大致明白其流程和使用方式. 过程坎坷, 好在最后还是成功运用到了 ...
- C#-等待异步函数执行结果-将调用异步方法的函数变成非异步执行
先来简单了解一下async.await 使用async await 的前提条件:需要C# 5.0以上版本 .NET Framework 4.5以上 Visual Studio 2012以上. asyn ...
- 聪明的暴力枚举求abcde/fghij=n
目录 前言 一.题目 二.暴力初解 三.优化再解(借鉴bitmap) 总结 前言 枚举如何聪明的枚举?那就是优化啦!下面梳理之前做过的一个暴力枚举的题,想了蛮久最后把它优化了感觉还不错,算是比较聪明的 ...
- Java开发学习(四十)----MyBatisPlus入门案例与简介
一.入门案例 MybatisPlus(简称MP)是基于MyBatis框架基础上开发的增强型工具,旨在简化开发.提供效率. SpringBoot它能快速构建Spring开发环境用以整合其他技术,使用起来 ...
- Vue3 企业级优雅实战 - 组件库框架 - 3 搭建组件库开发环境
前文已经初始化了 workspace-root,从本文开始就需要依次搭建组件库.example.文档.cli.本文内容是搭建 组件库的开发环境. 1 packages 目录 前面在项目根目录下创建了 ...
- 【题解】CF919D Substring
题面传送门 解决思路: DP 与拓扑结合.\(f_{i,j}\) 表示到 \(i\) 位置 \(j\) 的最大次数. 将 \(a \sim z\) 转成数字 \(0\sim 25\) ,方便存储. 考 ...
- SpringBoot 08: SpringBoot综合使用 MyBatis, Dubbo, Redis
业务背景 Student表 CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COL ...
- centos ssh 连接缓慢
在连接apache,ssh,mysql等服务器时,如果出现连接过慢,可能的原因是dns 的反向查询.反向解析是防止假冒的IP连接服务器,把IP解析成域名,来提高安全性,看这个IP是否是伪造,这是dns ...
- i春秋GetFlag
进去是个提示界面,提示我们这是个迷你文件管理系统,我们需要登录然后下载文件再获得flag. 然后我们查看源码,没什么信息,点login进去查看源码,没什么信息 下方出现了一个substr(md5(ca ...
- 【Serverless】Unity快速集成认证服务实现邮件登录
概述: 认证服务可以为您的应用快速构建安全可靠的用户认证系统,您只需在应用中访问认证服务的相关能力,而不需要关心云侧的设施和实现. 本次将带来如何使用Unity编辑器快速集成认证服务SDK并实现邮箱 ...