I have this problem for a long time now, I have searched the web and SO in and out and didn't find a solution yet. I hope you can help me on that.
I have a parent-child relationship between two entities like the following:
@Entity
public class Parent {
// ...
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
private Set<Child> children = new HashSet<Child>();
// ...
}
@Entity
public class Child {
// ...
@ManyToOne(fetch = FetchType.LAZY)
private Parent parent;
// ...
}
The thing is that when I create a new child and assign it to a parent, the parent doesn't get updated when it is in the cache already.
Parent parent = new Parent();
em.persist(parent);
// ...
Child child = new Child();
child.setParent(parent);
em.persist(child);
parent.getChildren().size(); // returns 0
I have tried to use @PreUpdate to automatically add the child to the parent when the child is persisted, but in the case when we have 2 entity managers in 2 different threads (like in JBoss), the issue still exists, until we call em.refresh(parent)
So the question is - is there a way to smoothly eliminate the problem and ensure that parent.getChildren()
always return the up-to-date list of children?