java – Hibernate Error: a different object with the same identifier value was already associated with the session

java – Hibernate Error: a different object with the same identifier value was already associated with the session

Most probably its because the B objects are not referring to the same Java C object instance. They are referring to the same row in the database (i.e. the same primary key) but theyre different copies of it.

So what is happening is that the Hibernate session, which is managing the entities would be keeping track of which Java object corresponds to the row with the same primary key.

One option would be to make sure that the Entities of objects B that refer to the same row are actually referring to the same object instance of C. Alternatively turn off cascading for that member variable. This way when B is persisted C is not. You will have to save C manually separately though. If C is a type/category table, then it probably makes sense to be that way.

Just set cascade to MERGE, that should do the trick.

java – Hibernate Error: a different object with the same identifier value was already associated with the session

You only need to do one thing. Run session_object.clear() and then save the new object. This will clear the session (as aptly named) and remove the offending duplicate object from your session.

Leave a Reply

Your email address will not be published.