Hibernate SessionFactory Tutorial

Introduction

Hibernate is a popular Object-Relational Mapping (ORM) framework for Java applications. It simplifies the development of Java applications to interact with the database. One of the core components of Hibernate is the SessionFactory, which is used to create Session objects for interacting with the database. This tutorial will guide you through the process of setting up and using SessionFactory in a Hibernate application using a Book entity and demonstrate more about SessionFactory and its use cases.

Prerequisites

Before we start, ensure you have the following:

  • Java Development Kit (JDK) installed
  • Apache Maven installed
  • MySQL database installed and running (or any other relational database)
  • An IDE (such as IntelliJ IDEA, Eclipse, or VS Code) installed

Step 1: Setting Up the Project

1.1 Create a Maven Project

  1. Open your IDE and create a new Maven project.

  2. Configure the pom.xml file with the following content:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>hibernate-sessionfactory-example</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- Hibernate and JPA -->
        <dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>6.4.0.Final</version>
        </dependency>
        <dependency>
            <groupId>jakarta.persistence</groupId>
            <artifactId>jakarta.persistence-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <!-- MySQL Connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>

        <!-- SLF4J for logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.32</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.32</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>17</source>
                    <target>17</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

1.2 Configure Hibernate

Create a hibernate.cfg.xml file in the src/main/resources directory with the following content:

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_database_name</property>
        <property name="hibernate.connection.username">your_username</property>
        <property name="hibernate.connection.password">your_password</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
    </session-factory>
</hibernate-configuration>

Replace your_database_name, your_username, and your_password with your MySQL database credentials.

Step 2: Creating the Entity Class

Create a Book class in the com.example.hibernatecrud.model package:

package com.example.hibernatecrud.model;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String author;
    private double price;

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

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

Step 3: Creating the Utility Class

Create a HibernateUtil class in the com.example.hibernatecrud.util package:

package com.example.hibernatecrud.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            Configuration configuration = new Configuration();
            configuration.configure("hibernate.cfg.xml");
            configuration.addAnnotatedClass(com.example.hibernatecrud.model.Book.class);
            return configuration.buildSessionFactory(new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build());
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        getSessionFactory().close();
    }
}

Step 4: Using Hibernate SessionFactory

The SessionFactory is a crucial component in Hibernate. It is a factory for Session objects, which are used to perform CRUD operations and manage transactions. The SessionFactory is typically created once during application startup and kept for the entire application lifecycle.

4.1 Initializing SessionFactory

The SessionFactory is initialized from a configuration file (hibernate.cfg.xml). This file contains the database connection details and Hibernate-specific settings.

4.2 Creating and Using Sessions

A Session is created from the SessionFactory and is used to perform database operations. Here’s how you can use the SessionFactory to perform various operations with the Book entity.

4.3 Example: Save a Book

import com.example.hibernatecrud.model.Book;
import com.example.hibernatecrud.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class SaveBookExample {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();

        Book book = new Book();
        book.setTitle("Hibernate in Action");
        book.setAuthor("Gavin King");
        book.setPrice(49.99);

        session.save(book);

        transaction.commit();
        session.close();
        HibernateUtil.shutdown();
    }
}

4.4 Example: Get a Book

import com.example.hibernatecrud.model.Book;
import com.example.hibernatecrud.util.HibernateUtil;
import org.hibernate.Session;

public class GetBookExample {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Book book = session.get(Book.class, 1L); // Assume this ID exists in the database

        if (book != null) {
            System.out.println("Title: " + book.getTitle());
        } else {
            System.out.println("Book not found");
        }

        session.close();
        HibernateUtil.shutdown();
    }
}

4.5 Example: Update a Book

import com.example.hibernatecrud.model.Book;
import com.example.hibernatecrud.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class UpdateBookExample {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();

        Book book = session.get(Book.class, 1L); // Assume this ID exists in the database
        if (book != null) {
            book.setPrice(39.99);
            session.update(book);
        }

        transaction.commit();
        session.close();
        HibernateUtil.shutdown();
    }
}

4.6 Example: Delete a Book

import com.example.hibernatecrud.model.Book;
import com.example.hibernatecrud.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class DeleteBookExample {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();

        Book book = session.get(Book.class, 1L);

        // Assume this ID exists in the database
        if (book != null) {
            session.delete(book);
        }

        transaction.commit();
        session.close();
        HibernateUtil.shutdown();
    }
}

Use Cases of SessionFactory

  1. Single Point of Configuration: The SessionFactory provides a single point for configuration and initialization of Hibernate settings and mappings.
  2. Creating Sessions: The primary role of the SessionFactory is to create Session instances. A Session is used to interact with the database.
  3. Application-Wide Singleton: The SessionFactory is designed to be an application-wide singleton shared across the application. It is typically created during application startup and kept for the entire lifecycle of the application.
  4. Caching: SessionFactory can provide session caching functionality. It can be configured to use a second-level cache for better performance in read-heavy applications.
  5. Connection Pooling: The SessionFactory can manage database connection pooling, which helps in efficiently managing the database connections in a multi-threaded environment.

Conclusion

In this tutorial, we covered the setup and use of the Hibernate SessionFactory to manage database operations. We demonstrated how to configure Hibernate, create a SessionFactory, and use it to perform CRUD operations with a Book entity. The SessionFactory is a critical component in Hibernate, providing a centralized way to manage database sessions and configurations. By understanding and utilizing the SessionFactory, you can effectively manage data persistence in your Java applications using Hibernate.

Comments