鉴于我设置了如下所示的 TransactionTemplate(在现有事务中启动新事务),如何防止父 (@Transactional
) 事务在代码内部回滚子事务抛出特定异常?本质上,模拟 @Transactional
的 noRollbackFor
参数。
@Transactional
public void foo() {
bar();
}
private void bar() {
TransactionTemplate transactionTemplate = new TransactionTemplate(platformTransactionManager);
transactionTemplate.setPropagationBehavior(PROPAGATION_REQUIRES_NEW);
transactionTemplate.execute(__ -> {
// ...
});
}
最佳答案
这对于 TransactionTemplate 来说是不可能的。
TransactionTemplate 不支持回滚规则。
请参阅:https://github.com/spring-projects/spring-framework/issues/25086
This is by design: TransactionTemplate does not support custom rollback rules. Technically TransactionTemplate isn't even aware of TransactionAttribute since that variant is an extended definition only supported by TransactionInterceptor (and therefore also living in the latter's package). The template operates on plain TransactionDefinition and uses fixed rollback behavior for all exceptions thrown from its callbacks, effectively RuntimeExceptions and Errors.
Alternatively, you may use the PlatformTransactionManager directly: Inject it, call getTransaction on it, perform some resource operations, then call commit in a finally block... and handle potential runtime exceptions any way you need to, without calling rollback. You may also selectively handle the outcome, as long as you eventually call commit (or rollback, for that matter) to complete the transaction.
更好地控制回滚内容和失败内容的替代解决方案是使用保存点,请参阅 https://dzone.com/articles/transaction-savepoints-in-spring-jdbc
关于spring - 如何在 `noRollbackFor` 上设置 `TransactionTemplate` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69329687/