spring事务报错Transaction rolled back because it has been marked as rollback-only

Transaction rolled back because it has been marked as rollback-only 阅读详情
AI摘要

文章详细分析了在Spring框架中,由于事务嵌套导致的Transactionrolledbackbecauseithasbeenmarkedasrollback-only异常的原因和解决办法。问题源于内层事务异常被外层事务捕获,内层事务被标记为回滚,但外层事务尝试提交,引发冲突。解决方案包括让内层事务抛出的异常被外层事务处理后再抛出,或者改变事务的传播行为。,

之前经常报"Transaction rolled back because it has been marked as rollback-only"这个异常

字面意思是"事务回滚了,因为它被标记了必须回滚",最开始完全不懂事务的嵌套,每次出现这个错误都想知道为什么,但是总是不能重现,后面反复折腾终于弄明白了怎么回事。

之前不能重现的一个重要原因是:同一个类,内部方法调用不走代理,spring基于注解的事务是基于代理的,不走代理,被调用的方法就不受事务管理代码的控制,自然无法重现问题.

测试代码:

TestController

 
  1. @Autowired

  2. TestRollbackService testRollbackService;

  3. @RequestMapping("/test1")

  4. public void test1(){

  5. try{

  6. testRollbackService.test1();

  7. }catch(Exception e){

  8. e.printStackTrace();

  9. }

  10. }

TestRollbackServiceImpl

 
  1. @Autowired

  2. StudentMapper studentMapper;

  3. @Autowired

  4. TestTransactionService testTransactionService;

  5. @Transactional(rollbackFor = Exception.class)

  6. public void test1(){

  7. Student studentSelect = new Student();

  8. studentSelect.setId(new Long(1));

  9. Student student = studentMapper.selectByPrimaryKey(studentSelect);

  10. try{

  11. testTransactionService.test2();

  12. }catch(Exception e){

  13. e.printStackTrace();

  14. }

  15. }

TestTransactionServiceImpl

 
  1. @Autowired

  2. StudentMapper studentMapper;

  3. @Transactional(rollbackFor = Exception.class)

  4. public void test2(){

  5. Student studentForInsert = new Student();

  6. studentForInsert.setId(new Long(19));

  7. studentForInsert.setName("测试11");

  8. studentForInsert.setScore(new BigDecimal(69));

  9. studentMapper.updateByPrimaryKey(studentForInsert);

  10. System.out.println(1/0);

  11. }

TestRollbackService.test1(方法A)中调用了TestTransactionService.test2(方法B),上述代码可以触发回滚异常的报错

两个方法都加了事务注解,并且两个方法都会受到到事务管理的拦截器增强,并且事务传播的方式都是默认的,也就是REQUIRED,当已经存在事务的时候就加入事务,没有就创建事务。这里A和B都受事务控制,并且是处于同一个事务的。

A调用B,A中抓了B的异常,当B发生异常的时候,B的操作应该回滚,但是A吃了异常,A方法中没有产生异常,所以A的操作又应该提交,二者是相互矛盾的。

spring的事务关联拦截器在抓到B的异常后就会标记rollback-only为true,当A执行完准备提交后,发现rollback-only为true,也会回滚,并抛出异常告诉调用者。

程序时序图如下:

1.程序入口

程序入口肯定是代理类,这里走是cglib的代理

入口方法:

org.springframework.aop.framework.CglibAopProxy.DynamicAdvisedInterceptor#intercept

该方法中

retVal = (new CglibAopProxy.CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy)).proceed();

继续调用

org.springframework.aop.framework.ReflectiveMethodInvocation#proceed

然后到了事务管理的拦截器

org.springframework.transaction.interceptor.TransactionInterceptor#invoke

 
  1. @Nullable

  2. public Object invoke(MethodInvocation invocation) throws Throwable {

  3. Class<?> targetClass = invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null;

  4. Method var10001 = invocation.getMethod();

  5. invocation.getClass();

  6. return this.invokeWithinTransaction(var10001, targetClass, invocation::proceed);

  7. }

2.invokeWithinTransaction(事务管理的主方法)

 
  1. @Nullable

  2. protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass, TransactionAspectSupport.InvocationCallback invocation) throws Throwable {

  3. TransactionAttributeSource tas = this.getTransactionAttributeSource();

  4. TransactionAttribute txAttr = tas != null ? tas.getTransactionAttribute(method, targetClass) : null;

  5. PlatformTransactionManager tm = this.determineTransactionManager(txAttr);

  6. String joinpointIdentification = this.methodIdentification(method, targetClass, txAttr);

  7. Object result;

  8. if (txAttr != null && tm instanceof CallbackPreferringPlatformTransactionManager) {

  9. TransactionAspectSupport.ThrowableHolder throwableHolder = new TransactionAspectSupport.ThrowableHolder();

  10. try {

  11. result = ((CallbackPreferringPlatformTransactionManager)tm).execute(txAttr, (status) -> {

  12. TransactionAspectSupport.TransactionInfo txInfo = this.prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);

  13. Object var9;

  14. try {

  15. Object var8 = invocation.proceedWithInvocation();

  16. return var8;

  17. } catch (Throwable var13) {

  18. if (txAttr.rollbackOn(var13)) {

  19. if (var13 instanceof RuntimeException) {

  20. throw (RuntimeException)var13;

  21. }

  22. throw new TransactionAspectSupport.ThrowableHolderException(var13);

  23. }

  24. throwableHolder.throwable = var13;

  25. var9 = null;

  26. } finally {

  27. this.cleanupTransactionInfo(txInfo);

  28. }

  29. return var9;

  30. });

  31. if (throwableHolder.throwable != null) {

  32. throw throwableHolder.throwable;

  33. } else {

  34. return result;

  35. }

  36. } catch (TransactionAspectSupport.ThrowableHolderException var19) {

  37. throw var19.getCause();

  38. } catch (TransactionSystemException var20) {

  39. if (throwableHolder.throwable != null) {

  40. this.logger.error("Application exception overridden by commit exception", throwableHolder.throwable);

  41. var20.initApplicationException(throwableHolder.throwable);

  42. }

  43. throw var20;

  44. } catch (Throwable var21) {

  45. if (throwableHolder.throwable != null) {

  46. this.logger.error("Application exception overridden by commit exception", throwableHolder.throwable);

  47. }

  48. throw var21;

  49. }

  50. } else {

  51. TransactionAspectSupport.TransactionInfo txInfo = this.createTransactionIfNecessary(tm, txAttr, joinpointIdentification);

  52. result = null;

  53. try {

  54. result = invocation.proceedWithInvocation();

  55. } catch (Throwable var17) {

  56. this.completeTransactionAfterThrowing(txInfo, var17);

  57. throw var17;

  58. } finally {

  59. this.cleanupTransactionInfo(txInfo);

  60. }

  61. this.commitTransactionAfterReturning(txInfo);

  62. return result;

  63. }

  64. }

程序执行的是最后的else分支,步骤很清晰

1.获取 TransactionAttribute

2.基于TransactionAttribute获取TransactionManager

3.基于TransactionAttribute获取 joinpointIdentification(没研究什么作用)

4. 基于1,2,3创建的对象获取  TransactionAspectSupport.TransactionInfo,transactionInfo是TransactionAspectSupport的一个内部类

5.执行业务方法

6.抓到异常就回滚,并清除事务,然后向上抛异常;没有异常就清除事务,然后提交

对象之间的关联关系

3.各个对象的获取

TransactionManager的获取比较简单,程序里获取到的其实就是自己配置的bean

创建TransactionInfo的过程中要先获取TransactionStatus,TransactionStatus又需要拿到ConnectionHolder

3.1 createTransactionIfNecessary

org.springframework.transaction.interceptor.TransactionAspectSupport#createTransactionIfNecessary

 
  1. protected TransactionAspectSupport.TransactionInfo createTransactionIfNecessary(@Nullable PlatformTransactionManager tm, @Nullable TransactionAttribute txAttr, final String joinpointIdentification) {

  2. if (txAttr != null && ((TransactionAttribute)txAttr).getName() == null) {

  3. txAttr = new DelegatingTransactionAttribute((TransactionAttribute)txAttr) {

  4. public String getName() {

  5. return joinpointIdentification;

  6. }

  7. };

  8. }

  9. TransactionStatus status = null;

  10. if (txAttr != null) {

  11. if (tm != null) {

  12. status = tm.getTransaction((TransactionDefinition)txAttr);

  13. } else if (this.logger.isDebugEnabled()) {

  14. this.logger.debug("Skipping transactional joinpoint [" + joinpointIdentification + "] because no transaction manager has been configured");

  15. }

  16. }

  17. return this.prepareTransactionInfo(tm, (TransactionAttribute)txAttr, joinpointIdentification, status);

  18. }

3.2 获取TransactionStatus

这里先调用   status = tm.getTransaction((TransactionDefinition)txAttr)  创建TransactionStatus

org.springframework.transaction.support.AbstractPlatformTransactionManager#getTransaction

 
  1. public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition) throws TransactionException {

  2. Object transaction = this.doGetTransaction();

  3. boolean debugEnabled = this.logger.isDebugEnabled();

  4. if (definition == null) {

  5. definition = new DefaultTransactionDefinition();

  6. }

  7. if (this.isExistingTransaction(transaction)) {

  8. return this.handleExistingTransaction((TransactionDefinition)definition, transaction, debugEnabled);

  9. } else if (((TransactionDefinition)definition).getTimeout() < -1) {

  10. throw new InvalidTimeoutException("Invalid transaction timeout", ((TransactionDefinition)definition).getTimeout());

  11. } else if (((TransactionDefinition)definition).getPropagationBehavior() == 2) {

  12. throw new IllegalTransactionStateException("No existing transaction found for transaction marked with propagation 'mandatory'");

  13. } else if (((TransactionDefinition)definition).getPropagationBehavior() != 0 && ((TransactionDefinition)definition).getPropagationBehavior() != 3 && ((TransactionDefinition)definition).getPropagationBehavior() != 6) {

  14. if (((TransactionDefinition)definition).getIsolationLevel() != -1 && this.logger.isWarnEnabled()) {

  15. this.logger.warn("Custom isolation level specified but no actual transaction initiated; isolation level will effectively be ignored: " + definition);

  16. }

  17. boolean newSynchronization = this.getTransactionSynchronization() == 0;

  18. return this.prepareTransactionStatus((TransactionDefinition)definition, (Object)null, true, newSynchronization, debugEnabled, (Object)null);

  19. } else {

  20. AbstractPlatformTransactionManager.SuspendedResourcesHolder suspendedResources = this.suspend((Object)null);

  21. if (debugEnabled) {

  22. this.logger.debug("Creating new transaction with name [" + ((TransactionDefinition)definition).getName() + "]: " + definition);

  23. }

  24. try {

  25. boolean newSynchronization = this.getTransactionSynchronization() != 2;

  26. DefaultTransactionStatus status = this.newTransactionStatus((TransactionDefinition)definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);

  27. this.doBegin(transaction, (TransactionDefinition)definition);

  28. this.prepareSynchronization(status, (TransactionDefinition)definition);

  29. return status;

  30. } catch (Error | RuntimeException var7) {

  31. this.resume((Object)null, suspendedResources);

  32. throw var7;

  33. }

  34. }

  35. }

3.3 获取transactionStatus前先获取DataSourceTransactionObject

程序最上面: Object transaction = this.doGetTransaction(); 创建DataSourceTransactionObject对象,这是DataSourceTransactionManager的内部类

org.springframework.jdbc.datasource.DataSourceTransactionManager#doGetTransaction

 
  1. protected Object doGetTransaction() {

  2. DataSourceTransactionManager.DataSourceTransactionObject txObject = new DataSourceTransactionManager.DataSourceTransactionObject();

  3. txObject.setSavepointAllowed(this.isNestedTransactionAllowed());

  4. ConnectionHolder conHolder = (ConnectionHolder)TransactionSynchronizationManager.getResource(this.obtainDataSource());

  5. txObject.setConnectionHolder(conHolder, false);

  6. return txObject;

  7. }

这里还获取了ConnectionHolder对象,这里newConnectionHolder为false

获取的方法如下:

org.springframework.transaction.support.TransactionSynchronizationManager#getResource

 
  1. @Nullable

  2. public static Object getResource(Object key) {

  3. Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);

  4. Object value = doGetResource(actualKey);

  5. if (value != null && logger.isTraceEnabled()) {

  6. logger.trace("Retrieved value [" + value + "] for key [" + actualKey + "] bound to thread [" + Thread.currentThread().getName() + "]");

  7. }

  8. return value;

  9. }

看代码很有意思,好像是通过一个key获取的,类似于从一个池子里面拿东西一样,其实当A方法执行的时候并没有获取到ConnectionHolder,拿到的是null

org.springframework.transaction.support.TransactionSynchronizationManager#doGetResource

 
  1. private static Object doGetResource(Object actualKey) {

  2. Map<Object, Object> map = (Map)resources.get();

  3. if (map == null) {

  4. return null;

  5. } else {

  6. Object value = map.get(actualKey);

  7. if (value instanceof ResourceHolder && ((ResourceHolder)value).isVoid()) {

  8. map.remove(actualKey);

  9. if (map.isEmpty()) {

  10. resources.remove();

  11. }

  12. value = null;

  13. }

  14. return value;

  15. }

  16. }

resources对象其实是一个ThreadLocal,意思是同一个线程中拿到的ConnectionHolder是相同的

3.3 doBegin方法

org.springframework.jdbc.datasource.DataSourceTransactionManager#doBegin

 
  1. protected void doBegin(Object transaction, TransactionDefinition definition) {

  2. DataSourceTransactionManager.DataSourceTransactionObject txObject = (DataSourceTransactionManager.DataSourceTransactionObject)transaction;

  3. Connection con = null;

  4. try {

  5. if (!txObject.hasConnectionHolder() || txObject.getConnectionHolder().isSynchronizedWithTransaction()) {

  6. Connection newCon = this.obtainDataSource().getConnection();

  7. if (this.logger.isDebugEnabled()) {

  8. this.logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");

  9. }

  10. txObject.setConnectionHolder(new ConnectionHolder(newCon), true);

  11. }

  12. txObject.getConnectionHolder().setSynchronizedWithTransaction(true);

  13. con = txObject.getConnectionHolder().getConnection();

  14. Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);

  15. txObject.setPreviousIsolationLevel(previousIsolationLevel);

  16. if (con.getAutoCommit()) {

  17. txObject.setMustRestoreAutoCommit(true);

  18. if (this.logger.isDebugEnabled()) {

  19. this.logger.debug("Switching JDBC Connection [" + con + "] to manual commit");

  20. }

  21. con.setAutoCommit(false);

  22. }

  23. this.prepareTransactionalConnection(con, definition);

  24. txObject.getConnectionHolder().setTransactionActive(true);

  25. int timeout = this.determineTimeout(definition);

  26. if (timeout != -1) {

  27. txObject.getConnectionHolder().setTimeoutInSeconds(timeout);

  28. }

  29. if (txObject.isNewConnectionHolder()) {

  30. TransactionSynchronizationManager.bindResource(this.obtainDataSource(), txObject.getConnectionHolder());

  31. }

  32. } catch (Throwable var7) {

  33. if (txObject.isNewConnectionHolder()) {

  34. DataSourceUtils.releaseConnection(con, this.obtainDataSource());

  35. txObject.setConnectionHolder((ConnectionHolder)null, false);

  36. }

  37. throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", var7);

  38. }

  39. }

截取该方法的重要几行:

 
  1. Connection newCon = this.obtainDataSource().getConnection();

  2. if (this.logger.isDebugEnabled()) {

  3. this.logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");

  4. }

  5. txObject.setConnectionHolder(new ConnectionHolder(newCon), true);

先获取连接(java.sql.Connection),然后创建ConnectionHolder,newConnectionHolder设置为true,如果之前已经不为空了,newConnectionHolder就为false

如果newConnectionHolder 为 true,还需要将 connectionHolder放到threadLocal里面,让后面的方法可以获取到相同的ConnectionHolder,截取的代码如下:

 
  1. if (txObject.isNewConnectionHolder()) {

  2. TransactionSynchronizationManager.bindResource(this.obtainDataSource(), txObject.getConnectionHolder());

  3. }

到这里TransactionStatus就创建好了

3.3 获取TransactionInfo

org.springframework.transaction.interceptor.TransactionAspectSupport#prepareTransactionInfo

 
  1. protected TransactionAspectSupport.TransactionInfo prepareTransactionInfo(@Nullable PlatformTransactionManager tm, @Nullable TransactionAttribute txAttr, String joinpointIdentification, @Nullable TransactionStatus status) {

  2. TransactionAspectSupport.TransactionInfo txInfo = new TransactionAspectSupport.TransactionInfo(tm, txAttr, joinpointIdentification);

  3. if (txAttr != null) {

  4. if (this.logger.isTraceEnabled()) {

  5. this.logger.trace("Getting transaction for [" + txInfo.getJoinpointIdentification() + "]");

  6. }

  7. txInfo.newTransactionStatus(status);

  8. } else if (this.logger.isTraceEnabled()) {

  9. this.logger.trace("Don't need to create transaction for [" + joinpointIdentification + "]: This method isn't transactional.");

  10. }

  11. txInfo.bindToThread();

  12. return txInfo;

  13. }

细看 txInfo.bindToThread();

org.springframework.transaction.interceptor.TransactionAspectSupport.TransactionInfo#bindToThread

 
  1. private void bindToThread() {

  2. this.oldTransactionInfo = (TransactionAspectSupport.TransactionInfo)TransactionAspectSupport.transactionInfoHolder.get();

  3. TransactionAspectSupport.transactionInfoHolder.set(this);

  4. }

java.lang.ThreadLocal#get 

 
  1. public T get() {

  2. Thread t = Thread.currentThread();

  3. ThreadLocalMap map = getMap(t);

  4. if (map != null) {

  5. ThreadLocalMap.Entry e = map.getEntry(this);

  6. if (e != null) {

  7. @SuppressWarnings("unchecked")

  8. T result = (T)e.value;

  9. return result;

  10. }

  11. }

  12. return setInitialValue();

  13. }

bindToThread()的的作用是获取oldTransactionInfo,还有线程有关(具体原理未知)

4.B方法抛异常后的回滚操作

org.springframework.transaction.interceptor.TransactionAspectSupport#completeTransactionAfterThrowing

 
  1. protected void completeTransactionAfterThrowing(@Nullable TransactionAspectSupport.TransactionInfo txInfo, Throwable ex) {

  2. if (txInfo != null && txInfo.getTransactionStatus() != null) {

  3. if (this.logger.isTraceEnabled()) {

  4. this.logger.trace("Completing transaction for [" + txInfo.getJoinpointIdentification() + "] after exception: " + ex);

  5. }

  6. if (txInfo.transactionAttribute != null && txInfo.transactionAttribute.rollbackOn(ex)) {

  7. try {

  8. txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());

  9. } catch (TransactionSystemException var6) {

  10. this.logger.error("Application exception overridden by rollback exception", ex);

  11. var6.initApplicationException(ex);

  12. throw var6;

  13. } catch (Error | RuntimeException var7) {

  14. this.logger.error("Application exception overridden by rollback exception", ex);

  15. throw var7;

  16. }

  17. } else {

  18. try {

  19. txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());

  20. } catch (TransactionSystemException var4) {

  21. this.logger.error("Application exception overridden by commit exception", ex);

  22. var4.initApplicationException(ex);

  23. throw var4;

  24. } catch (Error | RuntimeException var5) {

  25. this.logger.error("Application exception overridden by commit exception", ex);

  26. throw var5;

  27. }

  28. }

  29. }

  30. }

txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());调用transactionManager进行rollback

org.springframework.transaction.support.AbstractPlatformTransactionManager#rollback

 
  1. public final void rollback(TransactionStatus status) throws TransactionException {

  2. if (status.isCompleted()) {

  3. throw new IllegalTransactionStateException("Transaction is already completed - do not call commit or rollback more than once per transaction");

  4. } else {

  5. DefaultTransactionStatus defStatus = (DefaultTransactionStatus)status;

  6. this.processRollback(defStatus, false);

  7. }

  8. }

进一步调自身的processRollback

org.springframework.transaction.support.AbstractPlatformTransactionManager#processRollback

 
  1. private void processRollback(DefaultTransactionStatus status, boolean unexpected) {

  2. try {

  3. boolean unexpectedRollback = unexpected;

  4. try {

  5. this.triggerBeforeCompletion(status);

  6. if (status.hasSavepoint()) {

  7. if (status.isDebug()) {

  8. this.logger.debug("Rolling back transaction to savepoint");

  9. }

  10. status.rollbackToHeldSavepoint();

  11. } else if (status.isNewTransaction()) {

  12. if (status.isDebug()) {

  13. this.logger.debug("Initiating transaction rollback");

  14. }

  15. this.doRollback(status);

  16. } else {

  17. if (status.hasTransaction()) {

  18. if (!status.isLocalRollbackOnly() && !this.isGlobalRollbackOnParticipationFailure()) {

  19. if (status.isDebug()) {

  20. this.logger.debug("Participating transaction failed - letting transaction originator decide on rollback");

  21. }

  22. } else {

  23. if (status.isDebug()) {

  24. this.logger.debug("Participating transaction failed - marking existing transaction as rollback-only");

  25. }

  26. this.doSetRollbackOnly(status);

  27. }

  28. } else {

  29. this.logger.debug("Should roll back transaction but cannot - no transaction available");

  30. }

  31. if (!this.isFailEarlyOnGlobalRollbackOnly()) {

  32. unexpectedRollback = false;

  33. }

  34. }

  35. } catch (Error | RuntimeException var8) {

  36. this.triggerAfterCompletion(status, 2);

  37. throw var8;

  38. }

  39. this.triggerAfterCompletion(status, 1);

  40. if (unexpectedRollback) {

  41. throw new UnexpectedRollbackException("Transaction rolled back because it has been marked as rollback-only");

  42. }

  43. } finally {

  44. this.cleanupAfterCompletion(status);

  45. }

  46. }

this.triggerBeforeCompletion(status) 这个方法好像释放了连接

B不是新事务,所以最后会执行  this.doSetRollbackOnly(status);

org.springframework.jdbc.datasource.DataSourceTransactionManager#doSetRollbackOnly

 
  1. protected void doSetRollbackOnly(DefaultTransactionStatus status) {

  2. DataSourceTransactionManager.DataSourceTransactionObject txObject = (DataSourceTransactionManager.DataSourceTransactionObject)status.getTransaction();

  3. if (status.isDebug()) {

  4. this.logger.debug("Setting JDBC transaction [" + txObject.getConnectionHolder().getConnection() + "] rollback-only");

  5. }

  6. txObject.setRollbackOnly();

  7. }

org.springframework.jdbc.datasource.DataSourceTransactionManager.DataSourceTransactionObject#setRollbackOnly

 
  1. public void setRollbackOnly() {

  2. this.getConnectionHolder().setRollbackOnly();

  3. }

这里可以看到最终设置的是connectionHolder的rollbackonly属性

5.A方法尝试提交时的操作

org.springframework.transaction.interceptor.TransactionAspectSupport#commitTransactionAfterReturning

 
  1. protected void commitTransactionAfterReturning(@Nullable TransactionAspectSupport.TransactionInfo txInfo) {

  2. if (txInfo != null && txInfo.getTransactionStatus() != null) {

  3. if (this.logger.isTraceEnabled()) {

  4. this.logger.trace("Completing transaction for [" + txInfo.getJoinpointIdentification() + "]");

  5. }

  6. txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());

  7. }

  8. }

同样的,这里调用transactionManager进行提交

org.springframework.transaction.support.AbstractPlatformTransactionManager#commit

 
  1. public final void commit(TransactionStatus status) throws TransactionException {

  2. if (status.isCompleted()) {

  3. throw new IllegalTransactionStateException("Transaction is already completed - do not call commit or rollback more than once per transaction");

  4. } else {

  5. DefaultTransactionStatus defStatus = (DefaultTransactionStatus)status;

  6. if (defStatus.isLocalRollbackOnly()) {

  7. if (defStatus.isDebug()) {

  8. this.logger.debug("Transactional code has requested rollback");

  9. }

  10. this.processRollback(defStatus, false);

  11. } else if (!this.shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {

  12. if (defStatus.isDebug()) {

  13. this.logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");

  14. }

  15. this.processRollback(defStatus, true);

  16. } else {

  17. this.processCommit(defStatus);

  18. }

  19. }

  20. }

这个方法判断了一些无法提交的情况,程序这里走第二个分支,部分代码如下:

 
  1. else if (!this.shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {

  2. if (defStatus.isDebug()) {

  3. this.logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");

  4. }

  5. this.processRollback(defStatus, true);

  6. }

判断条件为: 

1.全局不是rollbackonly的时候也提交(这个可能是一个配置的参数,配合在rollbackonly的时候也提交,也就是出现现在这种情况后,不用回滚,直接提交)   

2.并且全局是rollbackonly

org.springframework.transaction.support.DefaultTransactionStatus#isGlobalRollbackOnly

 
  1. public boolean isGlobalRollbackOnly() {

  2. return this.transaction instanceof SmartTransactionObject && ((SmartTransactionObject)this.transaction).isRollbackOnly();

  3. }

这里又要满足两个条件

1 .这里的transaction是DataSourceTransactionObject

DataSourceTransaction继承 JdbcTransactionObjectSupport

JdbcTransactionObjectSupport又实现 SmartTransactionObject,所以第一个条件满足

2. DatSourceTransactionObject的 RollbackOnly 的get和set方法如下

 
  1. public void setRollbackOnly() {

  2. this.getConnectionHolder().setRollbackOnly();

  3. }

  4. public boolean isRollbackOnly() {

  5. return this.getConnectionHolder().isRollbackOnly();

  6. }

之前B方法抛出异常的时候,就是调用的DataSourceTransactionObject的set方法设置rollbackonly为true,现在再用get方法获取,只要是同一个connectionHolder,A获取到的rollbackOnly就是true,就会触发回滚,执行   this.processRollback(defStatus, true);

org.springframework.transaction.support.AbstractPlatformTransactionManager#processRollback

 
  1. private void processRollback(DefaultTransactionStatus status, boolean unexpected) {

  2. try {

  3. boolean unexpectedRollback = unexpected;

  4. try {

  5. this.triggerBeforeCompletion(status);

  6. if (status.hasSavepoint()) {

  7. if (status.isDebug()) {

  8. this.logger.debug("Rolling back transaction to savepoint");

  9. }

  10. status.rollbackToHeldSavepoint();

  11. } else if (status.isNewTransaction()) {

  12. if (status.isDebug()) {

  13. this.logger.debug("Initiating transaction rollback");

  14. }

  15. this.doRollback(status);

  16. } else {

  17. if (status.hasTransaction()) {

  18. if (!status.isLocalRollbackOnly() && !this.isGlobalRollbackOnParticipationFailure()) {

  19. if (status.isDebug()) {

  20. this.logger.debug("Participating transaction failed - letting transaction originator decide on rollback");

  21. }

  22. } else {

  23. if (status.isDebug()) {

  24. this.logger.debug("Participating transaction failed - marking existing transaction as rollback-only");

  25. }

  26. this.doSetRollbackOnly(status);

  27. }

  28. } else {

  29. this.logger.debug("Should roll back transaction but cannot - no transaction available");

  30. }

  31. if (!this.isFailEarlyOnGlobalRollbackOnly()) {

  32. unexpectedRollback = false;

  33. }

  34. }

  35. } catch (Error | RuntimeException var8) {

  36. this.triggerAfterCompletion(status, 2);

  37. throw var8;

  38. }

  39. this.triggerAfterCompletion(status, 1);

  40. if (unexpectedRollback) {

  41. throw new UnexpectedRollbackException("Transaction rolled back because it has been marked as rollback-only");

  42. }

  43. } finally {

  44. this.cleanupAfterCompletion(status);

  45. }

  46. }

到这里  unexpectedRollback为true,就抛出了  "Transaction rolled back because it has been marked as rollback-only"这个异常了。

解决方案
原场景,内层事务的异常被外层事务捕获,内层被标记rollback,而外层提交,最后事务提交校验时抛出Transaction rolled back because it has been marked as rollback-only异常

@Transactional(rollbackFor = Exception.class)
public void methodA(){
    insert();
    System.out.println(1 / 0);
}

@Transactional(rollbackFor = Exception.class)
public void methodB(){
    try{
        methodA();
    }catch(Exception e){
        System.out.println("有异常");
    }
}



可以分两种情况来解决这个异常
如果我们需要内层异常的情况下,回滚整个事务,可以让内层事务抛出的异常被外层事务的try----catch处理,再抛出新的异常,或者外层不通过try—catch处理这个异常。
当然如果内层事务没有复用过,只是在这个地方使用,直接把内层的事务去了,让他和外层合并成一个事务也能解决这个问题。

@Transactional(rollbackFor = Exception.class)
public void methodA(){
    System.out.println(1 / 0);
}

@Transactional(rollbackFor = Exception.class)
public void methodB(){
    try{
        insert();
        methodA();
    }catch(Exception e){
        throw new Exception("存在异常")
    }
}



如果内层事务异常的情况下只回滚内层事务,修改内层事务的事务传播方式

@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
public void methodA(){
    System.out.println(1 / 0);
}

@Transactional(rollbackFor = Exception.class)
public void methodB(){
    try{
        insert();
        methodA();
    }catch(Exception e){
        System.out.println("有异常");
    }
}


 

@Transactional事务回滚异常:Transaction rolled back because it has been marked as rollback-only 本文主要探讨了一个常见的Spring框架中的事务管理问题,即事务回滚异常@Transactional。首先,通过问题描述,让读者了解这个问题的现象和影响。然后,通过原因分析,深入解析了导致这个问题的几种可能原因,包括异常示例代码和查看源码。最后,通过解决方案部分,给出了解决这个问题的几种方法,并推荐了最佳实践。通过本文,读者可以更好地理解Spring框架中的事务管理机制,并学会如何解决常见的事务回滚异常问题。 阅读详情

相关推荐

出现 Transaction rolled back because it has been marked as rollback-only 解决方法

出现 Transaction rolled back because it has been marked as rollback-only 解决方法

码农研究僧的博客 1万+

spring 事务问题:Transaction rolled back because it has been marked as rollback-only

问题描述: 同事测试时使用异常数据,代码报错但是并不是异常产生的错误,而出现: Transaction rolled back because it has been marked as rollback-only 中文翻译就是: 事务已回滚,因为它被标记成了只回滚 代码片段: // 我的代码 @Transactional(readOnly = true, rollbackFor = Exception.class) public String select(Stri

sunayn的博客 2万+

STGCN实战:从零构建PyTorch时空图卷积网络预测城市交通流

本文详细介绍了如何使用PyTorch从零构建时空图卷积网络(STGCN)进行城市交通流预测。通过将交通网络建模为图结构,并融合时间卷积与空间图卷积,STGCN能有效捕捉交通流的时空依赖性。文章提供了从数据预处理、核心模块(TimeBlock与STGCNBlock)搭建、模型训练到实战技巧的完整指南,帮助开发者快速掌握这一前沿的交通速度预测技术。

wasm7browser的博客 255

Spring事务管理报错:Transaction rolled back because it has been marked as rollback-only

之前经常报"Transaction rolled back because it has been marked as rollback-only"这个异常 字面意思是"事务回滚了,因为它被标记了必须回滚",最开始完全不懂事务的嵌套,每次出现这个错误都想知道为什么,但是总是不能重现,后面反复折腾终于弄明白了怎么回事。 之前不能重现的一个重要原因是:同一个类,内部方法调用不走代理,spring基...

qq_38478903的博客 7万+

DAC8568控制器实战:如何用STM32实现多通道同步输出(附完整代码)

本文详细介绍了如何使用STM32微控制器驱动TI的DAC8568多通道DAC控制器,实现高精度的多通道同步模拟信号输出。内容涵盖硬件设计要点、SPI时序精准配置、驱动层命令构建,并重点解析了通过LDAC引脚实现同步更新的核心策略,提供了完整的代码框架和实战案例,帮助工程师快速解决多通道同步输出的工程难题。

weixin_29179311的博客 185

手把手教你解决Kernel panic报错:init找不到的5种排查方法(附NFS挂载实战)

本文深入解析了Linux系统启动时出现“Kernel panic - not syncing: No working init found”报错的根本原因,并提供了五种系统性的排查方法。文章结合NFS挂载根文件系统的实战场景,详细阐述了从动态链接库依赖、内核引导参数、NFS权限配置、文件系统完整性到内核配置干扰的完整排查路径,帮助开发者快速定位并解决这一常见的系统启动故障。

weixin_29159995的博客 205

Spring事务回滚报错:Transaction rolled back because it has been marked as rollback-only

spring事务回滚实战

BugMan的博客 4917

卫星监测“America”级#两#栖#攻#击#舰#(LHA-6)出港

卫星监测“America”级#两#栖#攻#击#舰#(LHA-6)出港 前脚刚走,后脚又来,山姆大叔又来刷存在感,2020年7月28日,USS Ronald Reagan流窜在我国东海海区被卫星拍了下来: 2020年8月1日,最新卫星图像显示USS Ronald Reagan已经返回母港日本横须贺:距离其出港(2020年6月8日)已经过去了快两个月 然而事情并没有到此结束,“America”级#两#栖#攻#击#舰#(LHA-6)选择在 “八.一” 这个特殊的日子前后出港颇具挑衅的味道。 根据2020年

qq_46071146的博客 1575

Spring事务管理报错Transaction rolled back because it has been marked as rollback-only

spring事务分为声明式事务和编程式事务,若目标方法存在事务,spring会对bean生成一个代理对象,从日志来看是cglib的 入口98行springaop事务增强 TransactionAspectSupport在事务中的调用,执行代理类的目标方法触发invoke

赵KK的博客 1924

侧杆试验 - 高速撞击 - 显式动力学 - ANSYS Workbench

显式动力学是一种时间积分方法,用于在速度很重要时执行动态模拟。显式动力学考虑快速变化的条件或不连续事件,例如自由落体、高速撞击和施加的负载。由于这些“非线性动力学”已集成到模拟中,因此显式动力学是模拟高度瞬态物理现象的首选。有些侧面碰撞是指车辆侧向撞上路边的坚硬物体,如树木或电线杆。这通常是由于驾驶员失去控制、超速、误判拐角或在湿滑路面上打滑造成的。

jianqimingtian的博客 1295

NX二次开发-用户自定义资源栏选项卡RegisterActivationCallback

NX二次开发-用户自定义资源栏选项卡RegisterActivationCallback

阿飞2018 1401

Spring事务管理报错:Transaction rolled back because it has been marked as rollback-only

昨天一个应用了很久的功能突然报错500,追踪日志后发现是Spring的事务管理报了错。

xmbcc777的博客 2713

vue3:html2canvas+jspdf将页面以A4导出为PDF文件,解决内容截断+在分页处截断问题详细排查和解决教程(jsPDF + html2canvas A4分页截断、内容分页时存在截断)

html2canvas + jsPDF 解决内容截断问题,vue3 jspdf-html2canvas生成多页pdf防截断处理(包含代码),vue3解决html2canvas + jsPDF导出pdf分页内容截断问题,jsPDF + html2canvas A4分页截断 完美解决方案(含代码 + 案例),html页面导出pdf截断问题,html2canvas 与 jspdf 相结合生成 pdf 内容被截断的终极解决方案,提供html2canvas+jsPDF将HTML页面以A4纸方式导出为PDF后,内容分页

✅ 精选推荐文章 2253

Transaction rolled back because it has been marked as rollback-only报错分析

这个错误是 Spring 事务管理中的典型问题,通常发生在嵌套事务场景中。核心原因是:内部事务操作触发了回滚标记,但外部事务尝试提交时被强制回滚。

weixin_43229159的博客 336

YOLO26涨点改进 | 小目标损失函数独家改进篇 | TGRS 2025 | 引入AdaFocalLoss损失函数,改进小目标检测,自适应聚焦小目标与样本分布不平衡,提升检测精度与训练稳定性

目录一、前言:YOLO26原生损失函数在小目标检测中的核心痛点(涨点瓶颈)1.1 小目标权重不足,聚焦能力薄弱1.2 样本分布不平衡适配性差,正负样本权重失衡1.3 训练不稳定,易出现梯度消失/震荡1.4 未区分小目标与背景的冗余干扰,误检率高二、TGRS 2025顶刊灵感解析:自适应聚焦损失的核心逻辑三、全网独家创新:AdaFocalLoss损失函数设计与YOLO26适配(核心重点,可复现)3.1 AdaFocalLoss函数整体设计(独家设计,清晰可复现)3.2 各核心模块详细设计(独家创新,可直接复现

qq_36130719的博客 214

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

有趣的事务嵌套问题

事务被回滚,因为它被标记为仅回滚。

QJY1437758743的博客 1023

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

Spring嵌套事务异常Transaction rolled back because it has been marked as rollback-only

嵌套事务出现的BUG

qq_42706375的博客 5583

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

Java报错Transaction rolled back because it has been marked as rollback-only

当外层方法(如 ServiceA.methodA())和内层方法(如 ServiceB.methodB())都开启了事务,且使用默认的事务传播行为 REQUIRED(即加入当前事务,若没有则新建),两者会共享同一个事务。外层方法 methodA() 捕获了异常(或未处理异常),并尝试提交事务,但此时事务已被标记为 rollback-only,Spring 会强制回滚并抛出此错误。标记回滚:内层事务抛出异常后,事务被标记为 rollback-only,外层事务无法覆盖此标记。// 独立事务,回滚不影响外层。

weixin_43203976的博客 2007

spring 注解事务遇到的大坑(查日志报Transaction rolled back because it has been marked as rollback-only,嵌套事务)

说我遇到的问题前请大家回顾一下spring的注解标注事务的几种,主要看标红的,其他的以后项目中用到在说,这个链接有对于嵌套事务的介绍 注解 解释 REQUIRED 表示业务方法需要在一个事务中处理,如果业务方法执行时已经在一个事务中,则加入该事务,否则重新开启一个事务。这也是默认的事务传播行为 NOT_SUPPORTED 声明业务方法不需要事务,如果业务方法执行时已经在一个事务中,则事务被挂起,等方法执行完毕后,事务恢复进行 REQUIRES_NEW 表明业务方法需要在一个单独的.

胖墩的IT博客 3165

Transaction rolled back because it has been marked as rollback-only 异常处理

从 rollback-only异常中分析下事务中propagation的应用和理解 rellback-only异常场景描述 项目已经过去很久了,今天突然间出现一个BUG,我开发的接口自己这边运行很正常,但是别人调用的时候,在方法结束后进行事务提交时报错: Transaction rolled back because it has been marked as rollback-onl...

Amos技术足迹 5961

Spring事务错误:Transaction rolled back because it has been marked as rollback-only

报错信息:Transaction rolled back because it has been marked as rollback-only 看来是spring框架中的事务管理报错:事务回滚了,因为它被标记为回滚状态。 模拟代码: Class ServiceA { @Autowired private ServiceB b; @Transactional public void a() { try { b.b()

D_A_I_H_A_O的博客 1470

SpringBoot程序报错事务回滚异常:Transaction rolled back because it has been marked as rollback-only

今天在测试环境中,测试一个功能的时候,发现了一个报错问题:Transaction rolled back because it has been marked as rollback-only,大致意思是事务已经回滚,因为它已经被标记为仅回滚。到此,Transaction rolled back because it has been marked as rollback-only的报错问题就解决啦。使用上面注解标记内层方法之后,再次启动运行,就可以正常运行啦。

✅ Java 开发工程师 3139

Java Transaction silently rolled back because it has been marked as rollback-only问题解决

问题描述: org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only 问题分析: 1、嵌套的两个方法都加了@Transaction注解,事务嵌套导致了报错。 @Transactional public void test1(){ test2(); } @Transactional pub.

旭东怪的博客 3万+
上一篇: Centos 7 安装系列(11):Kibana
下一篇: Java中事务的传播机制和隔离级别
暗星涌动
博客等级 码龄8年 203粉丝 122原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

暗星涌动

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值