Tuesday, June 25, 2019

Merge Vs SaveOrUpdate In Hibernate

Hibernate: Merge vs SaveOrUpdate

  • We can use saveOrUpdate(Object) to add/update an object into database. If identifier exist it will update record else add new record.
  • But it give "NonUniqueObjectException" exception.if the Persistence Context already contains an entity reference with the same id "identifier" and of the same type i.e. load an object twice.  
  • The saveOrUpdate method triggers a SaveOrUpdateEvent which is handled by the DefaultSaveOrUpdateEventListener Hibernate event listener.
  • This method appears only in the Hibernate API.
  • its return void, void saveOrUpdate(Object object) throws HibernateException.
  •  saveOrUpdate() can use without transaction also, but mapped objects not getting saved if session is not flushed.
  • Hibernate saveOrUpdate() method, adds the entity object to persistent context and track any further changes.It saved any further changes at the time of committing transaction.
  • The main purpose of the merge method is to update a persistent entity instance with new field values from a detached entity instance.
  • use same as saveOrUpdate(Object) but to avoid the "NonUniqueObjectException" exception, we should use the merge(object) method.
  • merge(object) method offered by the JPA EntityManager and inherited by the Hibernate Session as well.
  • The merge() method triggers a MergeEvent which is handled by the DefaultMergeEventListener Hibernate event listener.
  • merge() method, Copy the state of the given object onto the persistent object with the same identifier.
  • merge() mthhod, Return the persistent instance. 
  • Object merge(Object object) throws HibernateException
  • The merge operation can only be called within a transaction, an exception will be thrown outside of a transaction.

NonUniqueObjectException:  while you have two objects with same identifier means id in session or in Persistence Context. And you are trying to save this by using update() or saveOrUpdate() methods. it will give NonUniqueObjectException exception.

Solution-1: To resolve this issue either you can use merge().
Solution-2: First you can use evict(detach) for same object so evict() will remove that object from session. and than load the object and make changes than use update() or saveOrUpdate(). Now it will not give this exception. 

Related Tutorials

No comments:

Post a Comment