I’m having problems with a NonUniqueObjectException thrown by Hibernate.
Reading the docs, and this blog post, I replaced the call from update() to merge(), and it solved the problem.
I believe I understand the reason for the exception, and why changing the method fixed the problem, in terms of disconnected objects and session boundaries.
My question is : given that merge() will always resolve to the session object, or retrieve it if it doesn’t exist, is calling merge() generally a safer alternative than update()?
What is the downside of using merge() over update()?
As a way to avoid NonUniqueObjectException, yes. I think it explains why JPA does not allow an update method.
An unadvised user may think he or she has a fresh managed entity. Something like
And if your persistence context does not contain your entity, maybe you do not want select-before-updating default behavior. But it can be avoided
…
This way you can update your entity without merge or update method. See this question for more information: Best way to update some fields of a detached object on Hibernate ?