I have some entities in a one-to-many
relationship.
The parent:
@Entity
@Cacheable(false)
@Table(name="form_area")
public class FormArea {
@OneToMany(fetch = FetchType.LAZY, mappedBy="formArea", cascade = { CascadeType.MERGE, CascadeType.PERSIST })
private List<AssignableArea> assignableAreas = new ArrayList<AssignableArea>();
...
}
The child:
@Entity
@Cacheable(false)
@Table(name="assignable_area")
public class AssignableArea {
private @ManyToOne FormArea formArea;
...
}
The child object, AssignableArea also has getter/setter on the parent, FormArea.
When I re-parent using setFormArea()
, it seems successful, in that the database contains the correct information. But when I call getAssignableAreas()
on FormArea:
public List<AssignableArea> getAssignableAreas() {
return Collections.unmodifiableList(new ArrayList<>(assignableAreas));
}
I see the old list, before re-parenting. Why do I see the old, stale list, when I expect to see the updated list?
The most probable reason is that you've already loaded the FormArea
and its list of assignableAreas
, and you only updated one side of the association, so the other side stays as it was loaded: it's your responsibility to maintain both sides of the association if it matters to you.
If you start a new transaction and reload the FormArea, its list will contain the correct elements.