从 beforeCompletion TransactionSynchronization 回滚事务?
Rolling Back a transaction from beforeCompletion TransactionSynchronization?
我正在使用 Spring TransactionSynchronizationManager
注册一个 beforeCompletion
回调,如下所示:
@Transactional
public void doTransaction() {
//do DB stuff
updateDB();
//register a synchronization
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void beforeCompletion() {
if(!isCallApiSuccessful()) {
//rollback the transaction
}
}
});
}
问题是如何从 beforeCompletion
回调中回滚事务?抛出异常有用吗?
Would throwing an exception work?
不,它不会工作,因为 beforeCompletion()
用于清理资源。
根据文档,这是抛出异常的效果:
Throws:
java.lang.RuntimeException
- in case of errors; will be logged but not
propagated (note: do not throw TransactionException subclasses here!)
你可能应该实现 void beforeCommit(boolean readOnly)
来实现它,如果你想阻止提交,则在其中抛出一个 RuntimeException
。
根据文档,这是抛出异常的效果:
Throws:
java.lang.RuntimeException
- in case of errors; will be propagated to
the caller (note: do not throw TransactionException subclasses here!)
我正在使用 Spring TransactionSynchronizationManager
注册一个 beforeCompletion
回调,如下所示:
@Transactional
public void doTransaction() {
//do DB stuff
updateDB();
//register a synchronization
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void beforeCompletion() {
if(!isCallApiSuccessful()) {
//rollback the transaction
}
}
});
}
问题是如何从 beforeCompletion
回调中回滚事务?抛出异常有用吗?
Would throwing an exception work?
不,它不会工作,因为 beforeCompletion()
用于清理资源。
根据文档,这是抛出异常的效果:
Throws:
java.lang.RuntimeException
- in case of errors; will be logged but not propagated (note: do not throw TransactionException subclasses here!)
你可能应该实现 void beforeCommit(boolean readOnly)
来实现它,如果你想阻止提交,则在其中抛出一个 RuntimeException
。
根据文档,这是抛出异常的效果:
Throws:
java.lang.RuntimeException
- in case of errors; will be propagated to the caller (note: do not throw TransactionException subclasses here!)