JPA/@PostPersist @PostUpdate - 事务 [英] JPA / @PostPersist @PostUpdate - transaction
问题描述
我目前正在使用 @PostPersist
和 @PostUpdate
,并且在这些触发器中我正在持久化其他实体.问题是,这些触发器是否在同一个事务中,如果不是,是否可以强制执行?
I am currently working with @PostPersist
and @PostUpdate
, and in those triggers I am persisting additional entities. The question is, are those triggers in the same transaction and if not is it possible to force it ?
对我来说它是这样工作的.当我查看日志时,事务不存在(它在触发器启动之前提交),这阻止了我(没有 REQUIRES_NEW
来自注入 bean 的持久化方法)将其他实体保存在数据库.REQUIRED
属性被完全忽略,MANDATORY
属性不会抛出异常.
For me it works this way.
While I was looking through the logs the transaction isn't existing ( it's commited just before the trigger is launched ) which prevents me ( without REQUIRES_NEW
on the persisting method from injected bean ) from saving the additional entities in database.
REQUIRED
attribute is totally ignored, and MANDATORY
attribute do not throw an exception.
这可能是 JUnit 的问题(因为我处于开发阶段,没有在完整环境中测试行为.)?
Can it be the problem with JUnit ( since I am in the dev. phase and did not test the behavior on full env. ) ?
如果无法在此触发器上扩展事务,如何确保如果回滚发生在@PostPersist
和@PostUpdate
之前,这些操作也会被回滚.
If extending the transaction on this triggers is not possible, how to ensure that if the rollback occurs before the @PostPersist
and @PostUpdate
, those operations also will be rollbacked.
推荐答案
如果您使用的是 Spring,您可以随时向您当前的事务管理器注册一个 TransactionSynchronization
以在诸如提交等事件时被回调您当前正在运行的事务:
If you're using Spring you could always register a TransactionSynchronization
with your current transaction manager to be called back on events such as commits of your currently running transaction:
@PostPersist
void onPersist() {
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void beforeCommit(boolean readOnly) {
// do work
}
});
}
}
TransactionSynchronization
还在事务成功提交之后和事务完成之前/之后提供回调.
A TransactionSynchronization
also provides callbacks after a transaction has committed successfully and before/after a transaction completes.
如果您需要检查事务是否已提交或回滚,请使用afterCompletion(int status)
.
If you need to inspect if the transaction was committed or rolled back, use afterCompletion(int status)
.
详情请看TransactionSynchronization 的 JavaDoc.
这篇关于JPA/@PostPersist @PostUpdate - 事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!