我从规范中找到了以下信息。但对于不是英语母语的我来说还不够清楚。
The
PostPersist
andPostRemove
callback methods are invoked for an entity after the entity has been made persistent or removed. These callbacks will also be invoked on all entities to which these operations are cascaded. ThePostPersist
andPostRemove
methods will be invoked after the database insert and delete operations respectively. These database operations may occur directly after the persist, merge, or remove operations have been invoked or they may occur directly after a flush operation has occurred (which may be at the end of the transaction). Generated primary key values are available in thePostPersist
method.
我的问题是任何与事务相关的作业都可以在
@PostRemove
之后回滚?假设我的实体删除了
@PostRemove
上的一些离线文件class MyEntity {
@PostRemove
private void onPostRemove() {
// delete offline files related to this entity
// not restorable!
}
}
是否有可能从存储中删除的那些脱机文件和实体仍然留在数据库中? (通过回滚?)
最佳答案
是的,您的文件可能会被删除,而您的实体在回滚后仍留在数据库中。 @PostRemove
正在交易中。
如果您想绝对确定您的文件在且仅当事务成功完成时被删除,那么您应该在 commit()
之后删除文件。不使用回调方法成功。但是,如果您还需要确保当且仅当文件被删除时实体被删除,那么您就有问题了。您需要一种访问文件系统的事务性方式。
对于一个简单的解决方案,将您的文件移动到 to_be_deleted
- db-transaction 期间的文件夹。因此,您可以使用回调方法。文件终于在 commit()
时被删除成功并在失败时恢复。
如果您想更详细地说明它并且您的应用程序在 java EE 容器中运行,那么您可能需要查看 CDI events甚至在 jca adapter .如果你使用的是 Spring,你可以注册一个 TransactionSynchronizationAdapter
见 this answer .
关于jpa - @PostRemove 是否退出交易?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38561246/