buildSessionFactory() is deprecated in Hibernate 4

When working with NetBeans and Hibernate 4, you might encounter
a situation where NetBeans ‘strikes out’ code which had read buildSessionFactory() meaning it is deprecated in Hibernate 4.

So how to follow Hibernate 4 conventions and rewrite your buildSessionFactory() code to be compliant with Hibernate 4?

First, make sure you have these import lines:

import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

Then, go to the location of the code where SessionFactory instance is created.
It will probably look like this:

SessionFactory sessionFactory = new org.hibernate.cfg.Configuration().
configure().buildSessionFactory();

To get the same sessionFactory, you need to use code similar to the following in Hibernate 4 and above:

Configuration configuration = new Configuration();
configuration.configure();

ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().
applySettings(configuration.getProperties()).buildServiceRegistry();
SessionFactory sessionFactory = configuration.
buildSessionFactory(serviceRegistry);

4 Comments to “buildSessionFactory() is deprecated in Hibernate 4”

  1. Asraar 31 January 2014 at 6:54 pm #

    sir i am still getting the following error :
    Multiple markers at this line
    - The method buildServiceRegistry() is undefined for the type
    ServiceRegistryBuilder

  2. freakeresmind 13 May 2014 at 6:03 am #

    The use of buildServiceRegistry() is deprecated.
    The new updated code for latest hibernate 4 is as under:

    Configuration cfg = new Configuration();
    cfg.configure();

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();

    SessionFactory sf = cfg.buildSessionFactory(serviceRegistry);

    :) :)

  3. Akshay 28 May 2014 at 4:09 am #

    Hi,
    Thanks for the solution :). But when I was practicing here before, it was not showing problem like this. I used to type below code and it works.

    Configuration cfg = new Configuration().configure();
    SessionFactory factory = cfg.buildSessionFactory();
    Session session = factory.openSession();

    But now it is giving me a problem for buildSessionFactory() :(


Leave a Reply