Create SessionFactory in Hibernate 4

We can create SessionFactory in Hibernate 4 latest version, viz Hibernate 4.3.8 till now using the StandardServiceRegistryBuilder class. In prior version of hibernate we build the SessionFactory something like this
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

But the class org.hibernate.cfg.Configuration.buildSessionFactory() is deprecated in latest version of Hibernate. For more information you can go to the Hibernate Deprecated List

Project Structure & Required Libraries:-

create sessionfactory in hibernate 4

Code to create SessionFactory in Hibernate 4.3.8:-

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateSessionFactory {

	private static SessionFactory sessionFactory;

	static{
		try{

			Configuration configuration = new Configuration();

			configuration.configure("hibernate.cfg.xml");

			StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder();

			standardServiceRegistryBuilder.applySettings(configuration.getProperties());

			ServiceRegistry serviceRegistry = standardServiceRegistryBuilder.build();

			setSessionFactory(configuration.buildSessionFactory(serviceRegistry));
		}
		catch(HibernateException hex){
			hex.printStackTrace();
		}
	}

	public static SessionFactory getSessionFactory(){
		return sessionFactory;
	}

	public static void setSessionFactory(SessionFactory sessionFactory) {
		HibernateSessionFactory.sessionFactory = sessionFactory;
	}
	
	public static void shutdown()
	   {
	      getSessionFactory().close();
	   }
}

Example to test the SessionFactory:-

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class TestSessionFactory {

	public static void main(String[] args){
		
        System.out.println("create SessionFactory in hibernate 4.3.8");

		SessionFactory sessionFactory = HibernateSessionFactory.getSessionFactory();

		Session session = sessionFactory.openSession();

		Query query = session.createSQLQuery("show databases");

		@SuppressWarnings("unchecked")
		List list = query.list();

		for(Object object: list){
			System.out.println(object);
		}
		
		session.close();
	}
}

hibernate.cfg.xml




	

        com.mysql.jdbc.Driver
        jdbc:mysql://localhost:3306/test
        root
        

        org.hibernate.dialect.MySQLDialect

        true
		
	

So We can create SessionFactory in Hibernate 4, when migrating from Hibernate 3 to Hibernate 4 without using the deprecated classes.

Leave a Comment