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?
entityManager.persist(EntityA); entityManager.refresh(EntityA);
– Saulius Next