I have a parent child relationship in which the parent has a collection of children (a set to be specific). The child collection is setup with cascade="all-delete-orphan". When I initially save the parent element everything works as expected. However, when I update the parent and save again, all the children are re-saved.
For instance: A new parent is created with a set of children (child1, child2). When saved via hibernateTemplate's saveOrUpdate() everything works. However, if I then modify this collection by removing child2 and persist again, the new child set is now (child1, child2, child1) where it should be just (child1).
This behavior leads me to believe that the parent is losing its reference to the collection of children, and therefore when persisting all the children are re-saved. It seems the way to fix this is to not use the setter method for this child collection (and to modify the collection using add() and remove() functions instead), but unfortunately this setter is called implicitly in my application (Spring MVC is used to bind a multi-select form element to this collection, and the collection's setter is called by spring on the form submission). Overwriting this setter to not lose the reference (with the modified setter I have below) seems to be a hibernate no-no (based on this:
viewtopic.php?t=956859)
Modified setter (so as not to lose reference to child set) - not a good practice:
Code:
public void setTreatmentArms(Set<TreatmentArm> treatmentArms) {
this.treatmentArms.clear();
this.treatmentArms.addAll(treatmentArms);
}
Does anyone know how to circumvent this problem?