jpa - @PostRemove 是否退出交易?

标签 jpa lifecycle

我从规范中找到了以下信息。但对于不是英语母语的我来说还不够清楚。

The PostPersist and PostRemove 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. The PostPersist and PostRemove 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 the PostPersist 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,你可以注册一个 TransactionSynchronizationAdapterthis answer .

关于jpa - @PostRemove 是否退出交易?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38561246/

相关文章:

java - 如何获取命名查询的jpql?

eclipse - 使用 Tomcat 和 Eclipse 增强 DataNucleus JPA 运行时

.net - NHibernate 中的对象生命周期

java - 使用jpa映射多对多关系和可嵌入类

java - JPA + Hibernate + Spring + OneToMany 删除级联

java - 在 JPA 中声明一个没有类的持久单元

java - Lambda表达式匿名对象生命周期

android - 在房间数据库中添加列

Android 创建新的应用程序实例

jsf - 什么时候在 UIComponent 上调用 setValue 和 setSubmittedValue?