Tuesday 7 August 2018

Difference between Update and Merge methods in Hibernate with example

               As we discussed in the previous post, Hibernate Object has different states those are transient, persistent and detached.

             Both the update() and merge() methods are used to change the state of an object. That means we can call either update() or merge() to transfer an object from detached state to persistent state.
           
             We can  make the detached object to persist by reattaching to a session.  If the previous session is already been closed, it is also possible to create a new session and attach to that session. To reattach  to a session, we can use update() or merge() methods. Both are doing the same functionality, but there are few differences internally.


merge and update in hibernate
Merge and Update methods in hibernate


  • update() method:--   

         When we call update() method on session, if that session doesn’t contains same object (provided in update())  in cache then update() method successfully executed and the object been converted from detached state to persistent state.

         When we call update() method on any object, it internally checks, if that object is already existed in session cache or not — if currently updating object is already there in session cache then it throws an exception called NonUniqueObjectException and can not update the object.

Example:--

Take an example of Employee object, has property id, name and age. This example is the empty cache i.e no data exists in a session cache.

UpdateMethodExample.java,

package com.adnblog;
import com.adnblog.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class UpdateMethodExample {
    
     public static void main(String[] args) {
        
           Configuration configuration = new Configuration();
           configuration.configure("hibernate.cfg.xml");
           SessionFactory factory = configuration.buildSessionFactory();
           Session session = factory.openSession();
           Employee employee = (Employee) session.get(Employee.class, 121);
           session.close();

             // Employeee object is in detached state
           employee.setName("Kiran");
        
             // reattaching to session
           Session session2 = factory.openSession();
           Transaction tx = session2.beginTransaction();
           session2.update(employee);
           tx.commit();
     }
}

Output:--

Hibernate: select employee0_.id as id1_0_0_, employee0_.name as name2_0_0_, 
employee0_.age as age3_0_0_ from Employee employee0_ where employee0_.id=?

Hibernate: update employee set name=?, age=?, Where id=?

Example of already existed object in Session cache :--


       If already existed the same object in the Session cache, then update() method will throw NoUniqueObjectException, example shown in the below.

        Session session = factory.openSession();
        Employee employee = (Employee) session.get(Employee.class, 121);
        session.close();

        // Employeee object is in detached state
        employee.setName("Kiran");
        // reattaching to session
        Session session2 = factory.openSession();
        Transaction tx = session2.beginTransaction();
        session2.update(employee);
        tx.commit();

Output:--

Exception in thread "main" org.hibernate.NonUniqueObjectException: A different object 
with the same identifier value was already associated with the session : 
[com.adnblog.Employee#121]


  • merge() method :--


        The merge() method functionality is same as update() method. It can work both empty cache and existed cache, it doesn't throw any exception if same object is existed in the cache. The update() method will throw NonUniqueObjectException if same object exists in the session cache, already  discussed in the above example.

      The merge() method copies the current changes into the cache if object is already exists in the session cache.

Example:--

MergeMethodExample.java,

package com.adnblog;
import com.adnblog.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class MergeMethodExample {
    
     public static void main(String[] args) {
        
           Configuration configuration = new Configuration();
           configuration.configure("hibernate.cfg.xml");
           SessionFactory factory = configuration.buildSessionFactory();
           Session session = factory.openSession();
           Employee employee = (Employee) session.get(Employee.class, 121);
           session.close();
        
           // Employee object is in detached state
           employee.setName("Kiran");
           
           // reattaching to session 
           Session session2 = factory.openSession();
           Employee employee2 = session2.get(Employee.class, 121);
           Transaction tx = session2.beginTransaction();
           session2.merge(employee);
           tx.commit();
     }
}

Output:--
                It will update the employee details without exception.


Thank you for visiting blog.



Related Post:--
1) What are different states of an entity bean in Hibernate?
2) What is a Hibernate Caching ? Explain first level and second level cache in Hibernate
3) What is lazy loading in Hibernate? Explain with example
4) Hibernate JPA Cascade Types
5) Difference between save() and persist() method in Hibernate
6) What is the difference between get() and load() methods in Hibernate?
7) Hibernate Query Language(HQL) Examples
8) Hibernate Criteria Queries and Examples
9) Hibernate One to One Mapping Example - Annotation based

No comments:

Post a Comment