How to get Hibernate Session Factory Object (Singleton)


Use the following code for accessing Hibernate Session Factory in your projects.

import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateManager
// Hibernate utility class
{
  private static final SessionFactory sessionFactory;
  
  static {    //create sessionFactory only once    
    try {
      // creating the SessionFactory from hibernate.cfg.xml            
      sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
    catch (Throwable ex) {
           System.err.println(“SessionFactory initial creation error.”+ ex);
      throw new ExceptionInInitializerError(ex);
    }
  }
  public static SessionFactory getSessionFactory() {
     return sessionFactory;
  }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s