I'm having a problem with Hibernate that I'd like some advice on. I think I'm misunderstanding the object life cycle.
I have two objects, Source and Attribute, with a bidirectional many-to-many relationship. Both objects have java.util.Set of the other. There's a join table that uses the primary keys of each of the tables as a compound primary key.
In my Java code, I'm looping to create Sources. As soon as I enter the loop I open a session using SessionFactory. There's an inner loop to create Attribute children for the given Source. At the bottom of the loop I call saveOrUpdate for the Source, flush, and close the session. It works beautifully the first time through the loop. No worries.
Inside the inner loop where Attribute children are created and added to their Source parent, I check to see if one already exists in the database by doing a SELECT using HibernateCallback and Criteria. If it does, I add it to the Source's Set of Attributes. If not, I create a new one.
My problem arises when I loop through to load the second Source. I can see that some of the Attributes are new, because the Long primary key is null, but there are others that have values assigned because they were persisted by the first Source.
I can load up the second Source object, but when I saveOrUpdate I get the following exception:
Caused by: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [scds.model.Attribute#89]
An Attribute with Long id = 89 does indeed exist in the database. I thought that saveOrUpdate would be smart about persisting new Attributes and updating existing ones. What am I missing?
%