Problem:
With bidirectional relationships, if you do not update both sides in your object model, you might have an object tree that is not consistent with the Database. (See [url]http://www.hibernate.org/Documentation/InsideExplanationOfInverseTrue[/url]
Solution:
Update child and parent at the same time as follows:
In the child:
[code]
public void setParent(Parent parent)
{
// Do something only if parent changes.
if (this.parent != parent) {
// Remove child from current parent (if not null)
if (this.parent != null) this.parent.removeChild(this);
// Set new parent
this.parent = parent;
// Add child to new parent (if not null)
if (parent != null) {
parent.addChild(this);
}
}
}
[/code]
In the parent:
[code]
public void addChild(Child child) {
this.children.add(child);
child.setParent(this);
}
public void removeChild(Child child) {
this.children.remove(child);
child.setParent(null);
}
[/code]
Comments:
This works fine if the children collection in the parent has the "lazy" flag set to "false". As long as this flag is set to "true", you get a [code]Failed to lazily initialize a collection[/code] exception. The reason is that you try to add a child to the parent collection during the lazy initialization.
If you update the setParent method as follows, it works fine:
[code]
public void setParent(Parent parent)
{
// Do something only if parent changes.
if (this.parent != parent) {
// Remove child from current parent (if not null)
if (this.parent != null) this.parent.removeChild(this);
// Set new parent
this.parent = parent;
// Add child to new parent (if not null)
if (parent != null) {
try {
if (((PersistentCollection)parent.getChildren()).wasInitialized()) {
parent.addChild(this);
}
} catch (Exception e) {
}
}
}
}
[/code]
Question:
Could it be possible to synchronize the collection "add" methods during the lazy initialization?
_________________ Eric.
|