简体   繁体   中英

EclipseLink doesn't update entity relations after persist

Situation:
I have two entities related with a onetomany/manytoone relationship.

@Entity
public class EntityA{
  @ManyToOne()
  @JoinColumn(name="tableb_fk_id")
  private EntityB entityB;
}

@Entity
public class EntityB{
  @OneToMany(mappedBy="entityB")
  private List<EntityA> entityAList;
}

Imagine a PK called id and getter and setter being there for each class, too.

This is how i persist and read them:

public void persist(Object entity){
  entityManager.getTransaction().begin();
  entityManager.persist(entity);
  entityManager.getTransaction().commit();
}

public EntityB getEntityB(Object id){
  entityManager.getTransaction().begin();
  EntityB entity = entityManager.find(EntityB.class, id);
  entityManager.getTransaction().commit();
  return entity;
}

Now to get the persisted EntityB related to the persisted EntityA i call following:

getEntityB(entityA.getEntityB().getId());

Problem:
If i create an instance of EntityA and set a relation to an already existing instance of EntityB and persist this new instance all data are correctly saved to the database. But if i request the instance of EntityB from my EntityManager, it will not contain the just persisted instance of EntityA in its list. If i reload my persistence layer and flush it with the data from the database, it is there.

EntityA newEntityA = new EntityA();
EntityB existingEntityB = getEntityB(5); // just an example
newEntityA.setEntityB(existingEntityB);
perstist(newEntityA);
EntityB entityBforEntityA = getEntityB(newEntityA.getEntityB().getId());
entityBforEntityA.getEntityAList(); // <- does not contain newEntityA unless i restart

Question:
Why does my EclipseLink not update the newly persisted relation and how can i make it do that?

Stumbled upon this today. Let me welcome myself to the club.

As other answers pointed out, it's a cache problem. You can get around it without having to disable the shared cache by forcing EntityManager to fetch entity directly from database:

SomeEntityWithRelationship ent = em.find(SomeEntityWithRelationship.class, "someEntityPK", Map.of("javax.persistence.cache.retrieveMode", CacheRetrieveMode.BYPASS));

Another option is to simply use the relationship instead of directly persisting the related entity. Ie if SomeEntityWithRelationship has a Set<RelatedEntity> , directly add to that Set<RelatedEntity> instead of manually instantiating a RelatedEntity and calling entityManager.persis(relEntity) on it.

Examples use eclipselink.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM