Creating a generic SessionFactory provider class

Now, we will create a helper class, which will help us to set and get SessionFactory on demand.

We require SessionFactory at every point while working with hibernate. So, we will create a HibernateUtil.java class.

Tip

This is just a naming convention and not a hibernate standard but is used globally by developers and communities for the ease of use.

How to do it…

Here, we will create a Java file with the name HibernateUtil.java:

  1. Enter the following code in the HibernateUtil.java file:
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    public class HibernateUtil {
      private static final SessionFactory sessionFactory;
        
      static {
        try {
          // Create the SessionFactory from hibernate.cfg.xml
         sessionFactory = new Configuration().configure().buildSessionFactory();
    
          // Use code below for Hibernate version 4
          // Configuration configuration = new Configuration();
          // configuration = configuration.configure();
          // StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
          // builder = builder.applySettings(configuration.getProperties());
          // SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
        } catch (Throwable ex) {
          // Log the exception.
          System.err.println("SessionFactory creation failed." + ex);
          throw new ExceptionInInitializerError(ex);
        }
      }
    
      public static SessionFactory getSessionFactory() {
        return sessionFactory;
      }
    
      public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
      }
    }

How it works…

Here, we created the SessionFactory object and initialized it using the static block. The content inside the static block is executed only once. Here, it initializes the object of SessionFactory at the start of the program, and you can use it until the program's termination.

You can get the previously initially created SessionFactory object using the getSessionFactory() method. The main benefits of this method are the code's reusability and ease of use.

From now onwards for all demos, we will invoke HibernateUtil.getSessionFactory() method and also assume that SessionFactory has been successfully initialized.

The shutdown() method is used to close the sessionfactory. Once the close() method is invoked using the sessionfactory object, it close all caches and connection pools and releases all the connections to the database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.75.165