Spring JPA - One to Many - Re-parenting

NickJ :

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?

JB Nizet :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=82694&siteId=1