Hibernate Build SessionFactory Example

In this post, we show how to build a SessionFactory object in Hibernate 5 application.

SessionFactory is the factory class used to get the Session objects. SessionFactory is responsible to read the hibernate configuration parameters and connect to the database and provide Session objects. Usually, an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.

Create a Hibernate configuration file - hibernate.cfg.xml

Let's first create hibernate.cfg.xml to configure the database and mapping details. The configuration file contains information about the database and mapping file. Conventionally, its name should be hibernate.cfg.xml.

Build Hibernate SessionFactory 

Create a helper class to bootstrap hibernate SessionFactory. In most Hibernate applications, the SessionFactory should be instantiated once during application initialization. The single instance should then be used by all code in a particular process, and any Session should be created using this single SessionFactory.

The SessionFactory is thread-safe and can be shared; a Session is a single-threaded object. Let's create a HibernateUtil class to configure singleton SessionFactory and use it throughout the application.
The bootstrapping API is quite flexible, but in most cases, it makes the most sense to think of it as a 3 step process:
  1. Build the StandardServiceRegistry
  2. Build the Metadata
  3. Use those 2 to build the SessionFactory
package net.javaguides.hibernate.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {
    private static StandardServiceRegistry registry;
    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {
                // Create registry
                registry = new StandardServiceRegistryBuilder().configure().build();

                // Create MetadataSources
                MetadataSources sources = new MetadataSources(registry);

                // Create Metadata
                Metadata metadata = sources.getMetadataBuilder().build();

                // Create SessionFactory
                sessionFactory = metadata.getSessionFactoryBuilder().build();

            } catch (Exception e) {
                if (registry != null) {
        return sessionFactory;

    public static void shutdown() {
        if (registry != null) {
A complete example at https://www.javaguides.net/2018/11/hibernate-hello-world-tutorial.html.

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course