Hibernate Merge

Hibernate Merge

Merge is a method available in Hibernate which is used to update the existing records. However, it creates a copy from the passed entity objects and returns it. In other words, the merge() method is used to copy the state of the given entity object onto the persistent entity object with the same identifier. The Session interface provides the merge() method and is made available in org.hibernate.session package.

The merge() method is used when we want to change a detached entity into the persistent state again, with the detached entity’s changes updating into the database. The main aim of the merge() method is to update the changes in the database made by the persistent object.

There are two merge() methods available in Hibernate with different parameters:

  • merge(Object object)
  • merge(String entityName, Object object)

Both of the above methods perform the same functions.

SYNTAX of session.merge()

Employee employee = session.merge(emp);       

What is a detached object?

When the session of a persistent object has been closed, the object will be known as a detached object. As a detached object is no more associated with the Session, changes made to the data will not affect the database. The detached object can be reattached to a new session when needed.

Session s = sessionfactory.openSession();
session.save(emp)                   // The object emp is in the persistent state.
session.close(pay):               // The object emp is in the detached state. 

Example of session.merge() method

import com.app.mergeeg.Student;
 import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import org.hibernate.Transaction;
 import org.hibernate.cfg.Configuration;
 public class MergeEx {
     public static void main(String[] args) { 
         Configuration cfg = new Configuration();
         cfg.configure("hibernate.cfg.xml");
         SessionFactory factory = cfg.buildSessionFactory();
         Session session = factory.openSession();
         Student student = (Student) session.get(Student.class, 016);
         session.close(); 
          // Here, the student object is in a detached state 
         student.setName("Jyotika Sharma");
         // Here, reattaching to session 
         Session sess = factory.openSession();
         Student stud = sess.get(Student.class, 016);
         Transaction t = sess.beginTransaction(); 
         sess.merge(student);
         t.commit();
     }
 } 

Output

Example of session.merge() method



ADVERTISEMENT
ADVERTISEMENT