I have a tree with parent-child relation implemented with @OneToMany and @ManyToOne annotations.
Every child has @ManyToOne parent field, every parent has @OneToMany.
Both children and parents are heterogeneous, entities of any type may belong to parents of any parent type.
In this situation, Hibernate creates and manages the relation with an additional parent_child table, like it does for @ManyToMany relations.
Everything went well (I was able to create and delete any object), until I tried to implement changing the object parent, and got constraint violation.
The operation was implemented as follows:
oldParent.children.remove(child);
child.parent = newParent;
newParent.children.add(child);
As expected, Hibernate generates 3 change request: one to update the child.parent value, and two to update children collections for old and new parents.
The problem is in the wrong order of collection updates: it tries to add a new relation before removing the old one, which causes a constraint violation, since two parents are not allowed.
How can I force the right order of updates? Or how can I avoid using an additional table in this situation?