svz
svz

Reputation: 4588

Grails GORM: DuplicateKeyException on merge

I have two objects: User and Resume. Resume has a User user field. In my code I first get a user object and do some changes on it. In case a Resume.findByUser(user) exists I get the resume and do some changes there as well.
If I call user.save() and resume.save() I get an exception saying that there is another reference to the same object in the session, so I began to use merge().

When I call user.merge() the data is saved, but when I call resume.merge() I get this exception:
org.springframework.dao.DuplicateKeyException: a different object with the same identifier value was already associated with the session: [com.wizard.security.User#36]; nested exception is org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.wizard.security.User#36]

which I don't know what to do with. Looks like the problem is in the resume.user object which refers to the same one as the user.

I'll be grateful for help with this issue, thanks.

Upvotes: 2

Views: 2101

Answers (1)

jan.zanda
jan.zanda

Reputation: 146

Since GORM is built on hibernate, when you call merge on resume, it will cascade down to field user.

When you call user.merge() and then resume.merge() within one transaction, by the time of calling resume.merge() your user field has newer version in DB than the one held on resume instance.

I suggest you call resume.user.refresh() or resume.refresh() before making changes and merging.

Upvotes: 5

Related Questions