0

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?

2 Answers 2

2

After your first remove you should call flush. This will remove the initial parent relationship. Now if you reload the parent and child you should be able to associate them with each other.

Sign up to request clarification or add additional context in comments.

Comments

0

Actually you are NOT required to call flush() in any phase unless you need to. I cannot speak for Hibernate but JPA standard, the implementation must order the statements in an order that respects and plays by the constraints required by the domain.

Plese try the same case with Batoo JPA and let us know if it works for you. Otherwise we can help you.

3 Comments

Thank you, Hasan! Agreed, the implementation MUST order change events, but this one does not :-( Also thank for the link to Batoo. Will try it as soon as I have time.
BTW, is Batoo capable of creating/updating database schema from entity manager information?
Yes it is... You may use org.batoo.jpa.ddl property with DROP, CREATE, UPDATE, NONE options...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.