Most ORM's will behave this way.
The object in the cache is not updated from the database (an extra read that is not necessary). Also think of the object model and the persistence as separate. i.e. keep your object model consistent with itself and don't rely on the persistence mechanism to do this for you.
So if you want the object to be added to the collection then do that in the "setParent" code.
The best practice in this case is in fact to make one side of the relationship do all the work and let the other side defer onto it. Also I would suggest using field access rather than method access, that way you can customise methods with greater flexibility.
Add a method to parent called addChild
public void addChild(Child child) {
child.setParent0(this);
getChildren().add(individualNeed);
}
and then make setParent in Child:
public void setParent(Parent parent) {
parent.addChild(child);
}
setParent0 in Child is the property stter for parent on child.
public void setParent0(Parent parent) {
this.parent = parent;
}
I would also suggest that the "getChildren" method return an immutable collection so that developers don't inadvertantly not use this method (I learnt the hard way in all of this).
One more thing, you should have null checking code and other defensive pieces in the above code, I left it out for clarity.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…