Bootstrapping SessionFactory in Hibernate

If you have been watching previous Hibernate releases then you must have noticed that they have deprecated a lot of classes in quick succession. Deprecated classes are AnnotationConfiguration, ServiceRegistryBuilder and so on.

In this tutorial, I am giving few examples of building SessionFactory in Hibernate 5 and 6 without using deprecated classes mentioned above. I am using the latest available hibernate version of Hibernate 6.

1. Core Classes

As we know that in hibernate, the services are classes that provide Hibernate with pluggable implementations of various types of functionality. Specifically, they are implementations of certain service contract interfaces. To hold, manage and provide access to services, we use service registry.

Generally, the following classes are used as per the requirements for building SessionFactory.

  • ServiceRegistry: defines service registry contracts that applications are likely to want to utilize for configuring Hibernate behavior. The two popular implementations are BootstrapServiceRegistry, StandardServiceRegistry and SessionFactoryServiceRegistry.
  • BootstrapServiceRegistry: holds the services Hibernate will need during bootstrapping and at run time. For example, it can store the reference to ClassLoaderService, IntegratorService or StrategySelector through BootstrapServiceRegistry instance.
  • StandardServiceRegistry: hosts and manages services in runtime.
  • SessionFactoryServiceRegistry: is designed to hold services that need access to the SessionFactory, for example, EventListenerRegistry and StatisticsImplementor.
  • MetaData: an object containing the parsed representations of an application domain model and its mapping to a database.
  • MetadataSources: provides the source information to be parsed to form MetaData.

2. Building SessionFactory with XML Configuration

Generally, the hibernate.cfg.xml file contains the database connectivity and Enitity classes information. Additionally, we can have .hbm files as well.

<?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>
		<property name="hibernate.connection.driver_class">org.h2.Driver</property>
		<property name="hibernate.connection.url">jdbc:h2:mem:test</property>
		<property name="hibernate.connection.username">sa</property>
		<property name="hibernate.connection.password"></property>
		<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.format_sql">true</property>
		<property name="hibernate.hbm2ddl.auto">create-drop</property>
		<property name="hibernate.current_session_context_class">thread</property>
		<mapping class="com.howtodoinjava.demo.entity.EmployeeEntity" />
	</session-factory>
</hibernate-configuration>

To build the SessionFactory using the above XML configuration, we can follow the given code template.

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

  private static SessionFactory buildSessionFactory() {
    try {
      if (sessionFactory == null) {
        StandardServiceRegistry standardRegistry
            = new StandardServiceRegistryBuilder()
              .configure()
              .build();

        Metadata metadata = new MetadataSources(standardRegistry)
            .getMetadataBuilder()
            .build();

        sessionFactory = metadata.getSessionFactoryBuilder().build();
      }
      return sessionFactory;
    } catch (Throwable ex) {
      throw new ExceptionInInitializerError(ex);
    }
  }

  public static SessionFactory getSessionFactory() {
    return sessionFactory;
  }

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

Do not forget to close the session factory using close() method when the application shuts down.

sessionFactory.close()

3. Building SessionFactory with Properties Configuration

If we do not want to create hibernate.cfg.xml file then we can provide all the connection properties using a Map in the StandardServiceRegistryBuilder.applySettings() method.

SessionFactory sessionFactory = null;

Map<String, Object> settings = new HashMap<>();
settings.put("hibernate.connection.driver_class", "org.h2.Driver");
settings.put("hibernate.connection.url", "jdbc:h2:mem:test");
settings.put("hibernate.connection.username", "sa");
settings.put("hibernate.connection.password", "");
settings.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
settings.put("hibernate.current_session_context_class", "thread");
settings.put("hibernate.show_sql", "true");
settings.put("hibernate.format_sql", "true");
settings.put("hibernate.hbm2ddl.auto", "create-drop");


try {
  ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
      .applySettings(settings).build();

  Metadata metadata = new MetadataSources(standardRegistry)
      .addAnnotatedClass(EmployeeEntity.class)
      .getMetadataBuilder()
      .build();

  sessionFactory = metadata.getSessionFactoryBuilder().build();

} catch (Throwable ex) {
  throw new ExceptionInInitializerError(ex);
}

To add the metadata about entity classes and field mappings, we can use various methods provided by MetadataSources.

MetadataSources sources = new MetadataSources(standardRegistry)
    .addAnnotatedClass(MyEntity.class)
    .addAnnotatedClassName("org.hibernate.example.Customer")
    .addResource("org/hibernate/example/Order.hbm.xml")
    .addResource("org/hibernate/example/Product.orm.xml");

4. Conclusion

In this hibernate tutorial, we learned to create the SessionFactory using hibernate’s native support. We learned to provide the metadata using the XML file, and also properties files.

Happy Learning !!

Sourcecode on Github

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.