Hibernate 5 SessionFactory Example

In this tutorial I am going to explains example code of creating the Hibernate 5 SessionFactory. Hibernate 5 SessionFactory creation process is different from previous versions of Hibernate.

Hibernate 5 SessionFactory Example

Hibernate 5 SessionFactory Example - Learn the new way to creating SessionFactory in Hibernate 5

SessionFactory plays a major role in Hibernate framework and takes the responsibility to provide session object to the client program in thread safe way. SessionFactory  is heavy weight object and it is usually initialized at the start-up of the application. SessionFactory  uses the information defined in the hibernate.cfg.xml file bootstrap Hibernate ORM environment.

SessionFactory provides the Session object to Java program in thread safe way. The Session object provides the API for performing all the database related activities.

The SessionFactory provides a method getCurrentSession(), which returns the Session object. This method is used by client to get the Session object in a Java program.

The SessionFactory  is build only once in the lifespan of the application, so it should be a singleton object in the application.

Method of creating SessionFactory object is changed significantly in Hibernate 5. Following code was used in Hibernate 4 for creating the SessionFactory object:

try {

	Configuration configuration = new Configuration();
	configuration.configure();
	serviceRegistry = new ServiceRegistryBuilder().applySettings(
			configuration.getProperties()).buildServiceRegistry();
	sessionFactory = configuration.buildSessionFactory(serviceRegistry);

} catch (Throwable th) {

	System.err.println("Enitial SessionFactory creation failed" + th);

	throw new ExceptionInInitializerError(th);

}

But this old way of creating SessionFactory won't work in Hibernate 5.

Hibernate 5 SessionFactory Example

Now we will see the code example of creating the SessionFactory in Hibernate 5. Following code works well with Hibernate 5:

static {
   try {
	StandardServiceRegistry standardRegistry = 
       new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
	Metadata metaData = 
        new MetadataSources(standardRegistry).getMetadataBuilder().build();
	sessionFactory = metaData.getSessionFactoryBuilder().build();
   } catch (Throwable th) {
	System.err.println("Enitial SessionFactory creation failed" + th);
	throw new ExceptionInInitializerError(th);
  }
}

In Hibernate 5 StandardServiceRegistry class is used.

We have complete application using Hibernate 5 at the tutorial page: Hibernate 5 Annotation Example. On this page you will find video tutorial and full source code of developing program using Hibernate 5.