一尘不染

标记为仅回滚的事务:如何查找原因

spring

我在@Transactional方法中提交事务时遇到问题:

methodA() {
    methodB()
}

@Transactional
methodB() {
    ...
    em.persist();
    ...
    em.flush();
    log("OK");
}

当我从methodA()调用methodB()时,该方法成功通过,并且可以在日志中看到“确定”。但后来我明白了

Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:521)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
    at methodA()...
  1. 在异常中完全缺少methodB的上下文-我想这可以吗?
  2. methodB()中的某些内容将事务标记为仅回滚?我如何找到它?例如,是否有一种检查类似getCurrentTransaction().isRollbackOnly()?方法的方法-这样,我可以逐步检查方法并找到原因。

阅读 967

收藏
2020-04-14

共1个答案

一尘不染

当你将方法标记@Transactional为时,如果方法内部发生任何异常,则只会将周围的TX标记为回滚(即使你捕获了它们)。你可以使用@Transactional批注的其他属性来防止其回滚,例如:

@Transactional(rollbackFor=MyException.class, noRollbackFor=MyException2.class)
2020-04-14