Hello,
I have a problem and searched already a lot to try to solve this. It has to do with a NonUniqueObjectException, and it appears to me that quite a few developers have problems with this type of exception.
I have an application which has some business objects and uses Hibernate to store these objects into a database (actually quite simple).
When a single object must be persisted I have no problems and Hibernate is quite straightforward, but as soon as I begin with bidirectional associations I ran into problems.
I'm getting a NonUniqueObjectException when trying to save one of my objects. I will illustrate this with a simplified example:
I have an object A. This object has a one-to-many relationship with object B. Object B has a one-to-many relationschip with object C. I made the settings in the mapping files for these objects that I only have to save object A, and object B and C will be automatically saved by a cascade save-update.
The error occurs as soon as I have following situation:
A --> B1 --> C
A --> B2 --> C
So in this case both B1 and B2 have an assocation with C.
When I call session.save(A) i'm getting the NonUniqueObjectException. Hibernate wants to save B1 and therefore reattaches C and saves this, then B2 must be saved so C must be reattached, but C is already attached and the exception is thrown.
Do I miss something? I would presume that Hibernate detects that C is already attached and therefore does not try this a 2nd time. For all these objects the equals() and hashCode() methods are implemented.
How can you avoid such problems?
|