Monday, June 22, 2009

Hibernate cascade save-update NonUniqueObject Exception

If you have, say 3 hibernate entitites related as follows:
A --> mapped to --> collection of B : one-to-many
B --> mapped to --> C: many-to-one

If you do a session.update(A) - hibernate will attempt to update all the instances of B in the collection. If two instances of B point to the same instance of C --- you will get a NonUniqueObject Exception!

This is because Hibernate does not allow two instances of the same object in the same session.

The workaround to resolve this issue is to do a session.merge(A) instead of session.update(A)

This is another reason I feel it is better to avoid using save-update.

No comments:

Post a Comment