Hibernate Session merge () call

Hibernate Session merge () call

Explanation

  • Definition : The merge() method in Hibernate is used to update a detached entity in the database. Unlike the update() method, which can throw an exception if the entity already exists in the session, merge() ensures that the entity state is persisted correctly without conflicts.
  • Usage Scenario : When you have an entity that was previously in a persistent state, has become detached, and you want to reattach it to a new session and propagate its state to the database.

 Characteristics of Hibernate Session merge

  • Detachment Handling : It can be called on detached entities without causing exceptions related to entity state management.
  • Return Value : It returns a new persistent instance, which might be the same instance or a different one.
  • State Propagation : It copies the state of the given object onto the persistent object with the same identifier. If there is no persistent object currently associated with the session, it will load it from the database.

Hibernate Session merge

Example
Example in Java:
java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateMergeExample {
    public static void main(String[] args) {
        // Create SessionFactory
        SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml")
                .addAnnotatedClass(Student.class)
                .buildSessionFactory();

        // Create a transient entity
        Student student = new Student("John", "Doe", "john.doe@example.com");

        // First session: save the entity to make it persistent
        Session session1 = sessionFactory.openSession();
        session1.beginTransaction();
        session1.save(student);
        session1.getTransaction().commit();
        session1.close();

        // Detach the entity by closing the session
        // Modify the detached entity
        student.setFirstName("Jane");

        // Second session: merge the entity
        Session session2 = sessionFactory.openSession();
        session2.beginTransaction();
        Student mergedStudent = (Student) session2.merge(student);
        session2.getTransaction().commit();
        session2.close();

        // Verify the entity state
        System.out.println("Merged student: " + mergedStudent);

        sessionFactory.close();
    }
}

@Entity
@Table(name = "student")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "email")
    private String email;

    // Constructors
    public Student() {}
    public Student(String firstName, String lastName, String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    // Getters and setters
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    
    @Override
    public String toString() {
        return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
    }
}

Example of Hibernate Session merge

1. The Student entity is created and saved in the first session, making it persistent.

2. The session is closed, and the entity becomes detached.

3. The detached entity is modified (first name changed to “Jane”).

4. In the second session, the merge() method is used to reattach the entity and propagate its state to the database.

5. The merge() method returns a managed entity, which is printed to verify the update.

Homepage

Readmore