vmb
vmb

Reputation: 3028

Creating sessionFactory in Hql-Initialization

I have create a dbadapter for delaing with hibernate.Actually my class looks like this..

 public class DBAdapter {
    private static SessionFactory factory;
        private static final ThreadLocal<Session> threadSession = new ThreadLocal(); 

        public static Session OpenConnection() {
      if (factory == null) {
       factory = new Configuration().configure(
       "com/et/hibernatexml/hibernate.cfg.xml")
      .buildSessionFactory();
      }
     Session s = (Session) threadSession.get(); 
         if (s == null)
         { 
            s =factory.openSession(); 
            threadSession.set(s); 
          } 
        return s; 
 }
 public List selectQuery(String QueryString)
  {   try
      {
       Session session=OpenConnection();
       resultlist = query.list();
       }
       finally()
       {
        closeSession();
       }
   }
    public static void closeSession()
    {
      Session session = (Session) threadSession.get(); 
      threadSession.set(null); 
      if (session != null && session.isOpen()) { 
          session.flush(); 
          session.close(); 
      } 
}

For getting data from server ,i will do like this..

   DBAdapter ob=new DBAdapter();
   ob.setParameter("orgId", orgId);
   List list=ob.selectQuery(queryvalue);

My doubt is any issue by dealing like this.Especially because SessionFactory is static variable??

Upvotes: 0

Views: 695

Answers (1)

dkateros
dkateros

Reputation: 1594

You do not want more than one threads to create a session factory. It should be a singleton and is by design thread safe. The easiest way to do this with the code you provided is to use the synchronized keyword on the openConnection() method. However, there is no reason to synchronize the part of the code where you create a session and put it on the ThreadLocal instance as well. A rough solution would be like the following

public class DBAdapter {
    private static SessionFactory factory;
    private static final ThreadLocal<Session> threadSession = new ThreadLocal<Session>(); 

    private static synchronized SessionFactory getSessionFactory() {
        if(factory == null) {
            factory = new Configuration().configure("com/et/hibernatexml/hibernate.cfg.xml").buildSessionFactory();
        }
        return factory;
    }

    public static Session getSession() {
        Session s = (Session) threadSession.get(); 
        if (s == null) { 
            s = getSessionFactory().openSession(); 
            threadSession.set(s); 
        } 
        return s; 
     }
}

Upvotes: 1

Related Questions