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);

Leave a Reply