Explain openSession and getCurrentSession

Explain openSession and getCurrentSession

In Hibernate, both openSession and getCurrentSession are methods used to obtain a Session object, which is a primary interface for interacting with the database. However, they have significant differences in terms of their usage and lifecycle management.

1.  openSession:

  1. Usage:  This method always creates a new Session object.
  2. Lifecycle:  The session needs to be explicitly closed by the application code using the close() method.
  3. Transaction Management:  It doesn’t automatically participate in the current transaction context.

2.  getCurrentSession:

  • Usage:  This method provides a Session object that is bound to the current context (usually a thread).
  • Lifecycle:  The session is automatically closed at the end of the transaction or when the session context is flushed.
  • Transaction Management:  It automatically participates in the current transaction context.

openSession and getCurrentSession

Key Differences:

  • openSession creates a new session instance each time it is called, while getCurrentSession reuses a session associated with the current context.
  • openSession requires manual session management, including opening and closing, whereas getCurrentSession manages the session lifecycle automatically within the context of a transaction.

Java Example

Here is an example demonstrating the difference between openSession and getCurrentSession:

Create Hibernate Configuration File
1.  Create Hibernate Configuration File (hibernate.cfg.xml): 

xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        
        <!-- Enable Current Session Context -->
        <property name="hibernate.current_session_context_class">thread</property>
        
        <!-- Specify the HBMs and annotated classes here -->
        <mapping class="com.example.MyEntity"/>
        
    </session-factory>
</hibernate-configuration>

Create Entity Class
2.  Create Entity Class (MyEntity.java): 

java
package com.example;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class MyEntity {
    @Id
    private Long id;
    private String name;

    // Getters and setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Example
3.  Load Configuration and Build SessionFactory (HibernateUtil.java): 

java
package com.example;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Using openSession and getCurrentSession:
4.  Using openSession and getCurrentSession: 

java
package com.example;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class Main {
    public static void main(String[] args) {
        // Get the SessionFactory
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

        // Using openSession
        Session openSession = sessionFactory.openSession();
        Transaction openSessionTransaction = openSession.beginTransaction();
        try {
            MyEntity entity1 = new MyEntity();
            entity1.setId(1L);
            entity1.setName("Open Session");
            openSession.save(entity1);
            openSessionTransaction.commit();
        } catch (Exception e) {
            if (openSessionTransaction != null) {
                openSessionTransaction.rollback();
            }
            e.printStackTrace();
        } finally {
            openSession.close(); // Manually close the session
        }

        // Using getCurrentSession
        Session currentSession = sessionFactory.getCurrentSession();
        Transaction currentSessionTransaction = currentSession.beginTransaction();
        try {
            MyEntity entity2 = new MyEntity();
            entity2.setId(2L);
            entity2.setName("Current Session");
            currentSession.save(entity2);
            currentSessionTransaction.commit(); // Automatically closes the session at the end of the transaction
        } catch (Exception e) {
            if (currentSessionTransaction != null) {
                currentSessionTransaction.rollback();
            }
            e.printStackTrace();
        }
    }
}

Homepage

Readmore