Hibernate: different object with the same identifier value was already associated with the session [duplicate]

It would be easier to identify the exact cause if we can see the code where you’re assigning the role bean to both the user and then the group.

In general, what the exception tells us is that there are two versions of that role bean (two instances). The first one gets updated, then Hibernate hits the second one, and recognizes it’s the same identifier but a different detached version of the role.

Hibernate’s not sure which is correct, and under saveOrUpdate, it throws an exception to let you know.

Merge’s contract works differently, in that it will assume you meant to save it again (i.e., merge all my changes), and thus will reattach the second version, merge all changes, and save any updates.

I’ve blogged about SaveOrUpdate vs Merge with some more detail to explain what’s going on.

If you want to stick with SaveOrUpdate, you’re going to need to figure out what you’re doing in the assignment that’s causing a different instance of the role to be assigned to the user’s role collection versus to the groups.

Otherwise, if the effects of merge work for you (which is in line with the JPA standard), then use it.

Leave a Comment