Hibernate 4 create Session Factory: Example of creating Session Factory in Hibernate 4

Hibernate 4 tutorial of creating the instance of Session Factory in the Hibernate 4 based program. Learn the correct way to create the Session Factory object in the Hibernate 4 latest version Hibernate 4.3.0 final.

Hibernate 4 create Session Factory: How to create Session Factory in Hibernate 4?

In this tutorial I will explain you how you can create the Session Factory instance in your application? We are using the Hibernate 4.3.0.final build for creating the application.

Hibernate 4 is undoubtedly very popular and robust framework for creating enterprise application. Hibernate 4.3.0 is the JPA 2.1 compliant persistence provider.

Here in this tutorial I will explain you the code for creating the SessionFactory instance in your application. Hibernate 4.3.0 is the latest version of Hibernate and there are many changes in the API. One change is related to the SessionFactory and the way to initializing the session factory has changed. You if you are migrating your application to this version of Hibernate you will have to change the code. You should the latest code to create Session Factory object.

Here is the video tutorial of: "Is buildSessionFactory() deprecated in hibernate 4?"

Old way of creating the session factory:

SessionFactory sessionFactory = 
     new Configuration().configure().buildSessionFactory();

If you use the above code to create SessionFactory in the Hibernate 4.3.x then it won't work. It will throw the exception because the buildSessionFactory method is deprecated in the Hibernate 4. New API is developed to create the SessionFactory in Hibernate 4.

Now you can use the following code to create the SessionFactory in Hibernate 4:

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

Click Download Source Code

Source Code

 Configuration cfg = new Configuration().configure("hibernate.cfg.xml"); 
    StandardServiceRegistryBuilder sb = new StandardServiceRegistryBuilder();

  StandardServiceRegistry standardServiceRegistry = sb.build();
  SessionFactory sf = cfg.buildSessionFactory(standardServiceRegistry);

Check the tutorial for more details: Hibernate Example Step by Step in Eclipse.

More tutorials to Hibernate 4: