Monday, August 29, 2016

JPA: Persisting vs Merging Entities

Persisting entities
  • persist deals with new entities (passing a detached entity may end up with an exception.)
  • persist always causes INSERT SQL operation is executed (i.e. an exception may be thrown if the entity has already been inserted and thus the primary key violation happens.)
  • persist makes a previously removed entity managed again
  • persist makes the passed entity managed
  • persist does not return any value







Merging entities
  • merge deals with both new and detached entities
  • merge causes either INSERT or UPDATE operation according to the sub-scenario (on the one hand it is more robust, on the other hand this robustness needn't be required.)
  • merge throws an exception if a previously removed entity is passed
  • merge copies the state of the passed entity to the managed entity
  • merge returns the managed entity - the clone of the passed entity








So, when should I use persist and when merge?

persist
  • You want the method always creates a new entity and never updates an entity. Otherwise, the method throws an exception as a consequence of primary key uniqueness violation.
  • Batch processes, handling entities in a stateful manner (see Gateway pattern)
  • Performance optimization
merge
  • You want the method either inserts or updates an entity in the database.
  • You want to handle entities in a stateless manner (data transfer objects in services)
  • You want to insert a new entity that may have a reference to another entity that may but may not be created yet (relationship must be marked MERGE). For example, inserting a new photo with a reference to either a new or a preexisting album.

No comments:

Post a Comment