liveBook · Manning

Merge

As explained in Java Persistence with Spring Data and Hibernate epub

merge is a JPA EntityManager operation that copies the state of a detached or new entity instance into a managed instance in a persistence context.

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

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Traces identity lookup, state copying, managed-reference replacement, cascaded associations, SQL fetching, and flush effects.
Examples
Uses detached User updates and detached Item-Bid graphs to demonstrate reference replacement, cascades, joins, updates, and inserts.
What it assumes
Assumes entity instance states, identifiers, persistence contexts, transactions, and association mappings such as ManyToOne and OneToMany.
What you can do after
Apply it via EntityManager to store detached or transient changes and continue work through the returned managed instance.
How it connects
Connects detached state, transient state, persistence contexts, entity lifecycle, cascade types, lazy loading, and equality and hashCode.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.