Eclipselink:重新连接到数据库后,对实体 PrePersist/PreUpdate 的修改丢失

Eclipselink: Modifications to entity PrePersist/PreUpdate are lost after reconnection to database

我必须在实体之间建立一对多关系。当我持久化实体 A 时,我使用 PrePersist 和 PreUpdate 更改值并在实体 B 上创建实体并将它们与 A 相关联。

实体管理器打开时一切正常。如果我关闭它并重新打开它,实体 A "forgets" 关于实体 B。实体 B 条目仍然存在,但它们之间的 link 丢失了。

这是伪代码:

@PrePersist
@PreUpdate
void onCreate(EntityA a){
  EntityB b = new EntityB();
  persist b;
  a.getBList().add(b);
}

选中时 a.getBList() 创建后大小为 1。

当我关闭实体管理器并再次打开它时 a.getBList() 大小为 0,但 EnitiyB 仍然存在。就像 BList 永远不会持久化到实际数据库中。

有什么想法吗?

注意:这是一个过于简单化的示例。您可以找到实际代码 here.

答案基于给定的伪代码。

一个可能的原因是实现不支持这种方法。规范不要求支持修改生命周期回调方法中的关系(JPA 2 规范,3.5):

In general, the lifecycle method of a portable application should not invoke EntityManager or Query operations, access other entity instances, or modify relationships within the same persistence context. [43] A lifecycle callback method may modify the non-relationship state of the entity on which it is invoked.

如果 blist 是双向关系的非拥有方,也会出现此问题。如果是这种情况,则还应设置 EntityB 中的拥有方。

这是我这边的问题。已将连接列标记为可插入 = false、可更新 = false。回调方法仍然不是我所希望的答案。

对于遇到此问题的任何其他人,这是我到目前为止所学到的:

  • 回调方法(@PrePersist、@PreUpdate 等)不允许修改原始对象。任何更改都需要在保留之前通过其他方式完成。