Thursday, May 30, 2013

Hibernate: Building SessionFactory

In almost all applications, SessionFactory should be instantiated once during application initialization. This single instance should be used to create any session object in application.
SessionFactoty is thread safe and can be shared.

Ways to configureSessionFactory:

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

1.       When new Configuration() is called, Hibernate searches for a file named hibernate.properties in the classpath. If it’s found, all hibernate.* properties are loaded to the Configuration object.
2.       When configure() is called, Hibernate searches for a file named hibernate.cfg.xml in the class path, and exception is thrown if it is not found.
If settings in the XML configuration file and properties file are same (duplicate) then XML settings override the previous ones.
3.       If you wish to use a different file than hibernate.cfg.xml or to have Hibernate look in a subdirectory of your classpath for the XML configuration file, you must pass file name with complete path w.r.t. classpath as an argument of the configure() method.
SessionFactory sessionFactory
= new Configuration().configure("/config/test.cfg.xml").buildSessionFactory();

4.       You can always set additional configuration options or mapping file locations on the Configuration object programmatically, before building the SessionFactory object.
SessionFactory sessionFactory
= new Configuration().configure("/config/test.cfg.xml").setProperty().buildSessionFactory();



Example Code: HibernateUtil.java

package com.test.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class HibernateUtil {
    
    private static SessionFactory sessionFactory;
    
    static{
        try {
            sessionFactory = new Configuration().configure("com/test/resources/hibernate.cfg.xml").buildSessionFactory();
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }
    
    public static SessionFactory getSessionFactory(){
            return sessionFactory;
    }
    
    public static void shutDown(){
    getSessionFactory().close();
    }
    
}

No comments: