Explain Hibernate SessionFactory

Explain Hibernate SessionFactory

In Hibernate, the SessionFactory is a crucial interface that is responsible for creating Session objects. A Session object represents a single unit of work with the database, allowing for operations such as CRUD (Create, Read, Update, Delete) to be performed. The SessionFactory is designed to be instantiated once and then reused throughout the application. It is thread-safe and provides a cache of compiled mappings for a specific database.

Configuration of Hibernate SessionFactory

The configuration of the SessionFactory involves setting up the necessary properties to establish a connection with the database and defining the mapping between Java classes and database tables. This is typically done using a configuration file (e.g., hibernate.cfg.xml) or programmatically via a Configuration object.

Hibernate SessionFactory

Key Steps to Hibernate SessionFactory

1.  Create Hibernate Configuration File (hibernate.cfg.xml):  This XML file contains the database connection settings and mappings.

2.  Load Configuration and Build SessionFactory:  Use Hibernate’s Configuration class to load the configuration file and build the SessionFactory.

3.  Use the SessionFactory to Obtain Sessions:  The SessionFactory is used to create Session objects which are then used for database operations.

Create Hibernate Configuration Fil
Java Example
  Step-by-Step Example

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>
        
        <!-- Specify the HBMs and annotated classes here -->
        <mapping class="com.example.MyEntity"/>
        
    </session-factory>
</hibernate-configuration>


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;
    }
}

Load Configuration and Build SessionFactory
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;
    }
}

Example
4.  Use the SessionFactory to Obtain Sessions: 

java
package com.example;

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

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

        // Open a new Session
        Session session = sessionFactory.openSession();
        Transaction transaction = null;
        
        try {
            // Start a transaction
            transaction = session.beginTransaction();

            // Create a new MyEntity object
            MyEntity entity = new MyEntity();
            entity.setId(1L);
            entity.setName("Test Name");

            // Save the entity
            session.save(entity);

            // Commit the transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            // Close the session
            session.close();
        }
    }
}

Homepage

Readmore