merge is a JPA EntityManager operation for bringing detached or transient state into a persistence context. It copies values onto a managed instance and returns that managed instance; the supplied object remains detached or transient. section 10.3.4
A merge operation proceeds according to the supplied entity's identity and state:
- Checks for a managed instance with the same identifier; otherwise loads the entity from the database. section 10.3.4
- Copies the detached entity's values onto the loaded managed instance and returns that instance. section 10.3.4
- Creates a persistent instance for a transient object and inserts it when the persistence context synchronizes with the database. section 10.3.4
- Flushes changes from the returned reference; continuing to modify the original detached reference does not update the managed state. section 10.3.4
Merging a detached User
detachedUser.setUsername("johndoe"); em = emf.createEntityManager(); em.getTransaction().begin(); User mergedUser = em.merge(detachedUser); mergedUser.setUsername("doejohn"); em.getTransaction().commit(); em.close(); The transaction commits the change from mergedUser, while detachedUser is discarded as stale state.
Associations require explicit cascade configuration. CascadeType.DETACH and CascadeType.MERGE allow an Item's loaded bids to detach and merge transitively; merging can fetch the collection with a join and flush updates and inserts. section 13.1.2
