eclipselinkjpa-2.0

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


I have two entities with a one to many relationship between them. When I'm persisting EntityA I use PrePersist and PreUpdate to change values and create entities on EntityB and related them to EntityA.

Everything works fine while the EntityManager is open. If I close it and re-open it, EntityA "forgets" about EntityB. EntityB entries are still there, but the link between them is lost.

Here's the pseudo code:

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

When checked a.getBList() size is 1 after creation.

When I close the EntityManager and open it again a.getBList() size is 0, but the EnitiyB are still there. It is like BList is never persisted to the actual database.

Any ideas?

Note: This is an oversimplified example. You can find the actual code here.


Solution

  • Answer is based to given pseudo code.

    One possible reason is that implementation does not support this approach. Specification does not require support for modifying relationships in lifecycle callback method (JPA 2 Specification, 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.

    Also this issue can rise if blist is non-owning side of the bidirectional relationship. If that is the case then owning side in EntityB should also be set.