Tuesday, 7 August 2018

Difference Between update() and merge() Methods in Hibernate with Examples

                As we discussed in the previous post, a Hibernate object can exist in different states: transient, persistent, and detached.

Both the update() and merge() methods are used to reattach a detached object to a Hibernate session. In other words, they transition an object from the detached state to the persistent state.

A detached object can be made persistent again by reattaching it to a session. If the previous session has already been closed, you can create a new session and reattach the object to it. Hibernate provides the update() and merge() methods for this purpose.

Although both methods are used to reattach detached objects, they differ in how they work internally. We will discuss these differences in the following sections.


merge and update in hibernate
Merge and Update methods in hibernate


  • update() method:--   

         When we call the update() method on a Hibernate Session, it first checks whether an entity with the same identifier already exists in the session cache.

If the session does not contain an entity with the same identifier, the update() method executes successfully, and the detached object is reattached to the session, transitioning from the detached state to the persistent state.

However, if the session already contains an entity with the same identifier, the update() method throws a NonUniqueObjectException and the update operation fails.


Example:--

Consider an Employee object with the properties id, name, and age. In this example, the session cache is empty, meaning it does not contain any Employee objects.

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 an object with the same identifier already exists in the session cache, the update() method throws a NonUniqueObjectException, as shown in the example 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 provides functionality similar to the update() method. However, unlike update(), it works whether the session cache is empty or already contains an instance of the same entity. It does not throw a NonUniqueObjectException if an object with the same identifier already exists in the session cache. As discussed in the previous example, the update() method throws a NonUniqueObjectException in such cases.

If an object with the same identifier already exists in the session cache, the merge() method copies the state of the detached object into the persistent object managed by the current session.

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