HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Hibernate / Hibernate – How to build SessionFactory

Hibernate – How to build SessionFactory

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.

These classes are used to build session factory through the java code and if we use them in our application; they might work well but we will always see some annoying warnings about their depreciation.

In this tutorial, I am giving an example of building SessionFactory in Hibernate 5 without using deprecated classes mentioned above. I am using latest hibernate version i.e. Hibernate 5.4.17.Final, so you can make sure that you are using latest approach for building session factory.

1. Classes used in building SessionFactory

I have used following classes for building SessionFactory in hibernate.

  1. Configuration : In place of deprecated AnnotationConfiguration
  2. StandardServiceRegistryBuilder : In place of deprecated ServiceRegistryBuilder

How to build SessionFactory

Use below example code build the SessionFactory in hibernate. Feel free to tweak the code as per your need.

package com.howtodoinjava.hibernate.test;

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 SessionFactory sessionFactory = buildSessionFactory();

   private static SessionFactory buildSessionFactory() 
   {
      try 
      {
         if (sessionFactory == null) 
         {
            StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                  .configure("hibernate.cfg.xml").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();
   }
}

Where the configuration file is:

<?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="show_sql">true</property>
      <property name="hbm2ddl.auto">create-drop</property>
      <mapping class="com.howtodoinjava.hibernate.test.dto.EmployeeEntity"></mapping>
   </session-factory>
</hibernate-configuration>

I hope the above information will help you when migrating from hibernate 3.

Happy Learning !!

Sourcecode Download

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. vijay

    October 23, 2015

    why constructor is not private, you are trying to achieve singleton I guess.

    please add.

  2. Radu

    February 2, 2015

    [Off-topic] The title is misspelled. Hibarnate => Hibernate

    • Lokesh Gupta

      February 2, 2015

      OOPs !! Thanks for noticing and let me know.

  3. amar

    September 6, 2014

    Use resource on threadlocal instead of on class.

    • Lokesh Gupta

      September 6, 2014

      ???? Plz explain?

      • sreenath

        November 18, 2014

        I think Amar is trying to say this

        Threadlocal is used to create session for every thread.It will make sure that every user accessing web page will get its own session. So here threadlocal is used basically to provide different session to different thread.

        Source:http://www.coderanch.com/t/591556/ORM/databases/Importance-ThreadLocal-hibernate

Comments are closed on this article!

Search Tutorials

Hibernate Tutorial

  • Hibernate – Introduction
  • Hibernate – Hello World
  • Hibernate – Get/Fetch
  • Hibernate – Persist
  • Hibernate – Merge & Refresh
  • Hibernate – Get Entity Reference
  • Hibernate – BLOB
  • Hibernate – Save Update
  • Hibernate – Persistence LifeCycle
  • Hibernate – SessionFactory
  • Hibernate – Entities Equality
  • Hibernate – Cascade Types
  • Hibernate – Lazy Loading
  • Hibernate – Criteria Queries
  • Hibernate – HQL
  • Hibernate – Named Query
  • Hibernate – Mappings
  • Hibernate – First Level Cache
  • Hibernate – Second Level Cache
  • Hibernate – EhCache Configuration
  • Hibernate – OSCache Configuration
  • Hibernate – C3P0 Connection Pool
  • Hibernate – In memory Database
  • Hibernate – Bean Validation
  • Hibernate – Validator CDI
  • UnexpectedTypeException

Hibernate Annotations

  • Hibernate – JPA 2 Annotations
  • Annotations Vs Mappings
  • Hibernate – @Immutable
  • Hibernate – @NaturalId
  • Hibernate – @OneToMany
  • Hibernate – @ManyToMany
  • Hibernate – @OneToOne

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)