Spring + Hibernate : a different object with the same identifier value was already associated with the session
Use merge()
. The exception means that the current session is already aware of the entity you are passing. If not, check how you have overridden hashCode()
and equals()
- it should return different values for different entities.
You can also encounter this problem if you are doing a delete()
or update()
. The problem is likely to occur if you build the hibernate-mapped pojo yourself, perhaps from a DTO. This pojo now has the same identifier as one that is already in the Session
, and that causes the problem.
You now have two options. Either do what @Bozho said and first merge()
the object. That takes care of updating. For deleting, take the object returned by merge()
and delete it.
The other option is to first query the Session
using the id of the object and then delete or update it.