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
}
});
}
}
A 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 。
For details have a look at TransactionSynchronization's JavaDoc.
这篇关于JPA / @PostPersist @PostUpdate - 交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!