EntityManager.merge()
can insert new objects and update existing ones.
Why would one want to use persist()
(which can only create new objec
I found this explanation from the Hibernate docs enlightening, because they contain a use case:
The usage and semantics of merge() seems to be confusing for new users. Firstly, as long as you are not trying to use object state loaded in one entity manager in another new entity manager, you should not need to use merge() at all. Some whole applications will never use this method.
Usually merge() is used in the following scenario:
- The application loads an object in the first entity manager
- the object is passed up to the presentation layer
- some modifications are made to the object
- the object is passed back down to the business logic layer
- the application persists these modifications by calling merge() in a second entity manager
Here is the exact semantic of merge():
- if there is a managed instance with the same identifier currently associated with the persistence context, copy the state of the given object onto the managed instance
- if there is no managed instance currently associated with the persistence context, try to load it from the database, or create a new managed instance
- the managed instance is returned
- the given instance does not become associated with the persistence context, it remains detached and is usually discarded
From: http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html/objectstate.html