在Hql-Initialization中创建sessionFactory

时间:2013-01-29 09:19:17

标签: java hibernate static thread-safety sessionfactory

我已经用hibernate创建了一个用于delaing的dbadapter。实际上我的类看起来像这样..

 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(); 
      } 
}

为了从服务器获取数据,我会这样做..

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

我怀疑是这样处理的任何问题。特别是因为SessionFactory是静态变量??

1 个答案:

答案 0 :(得分:1)

您不希望多个线程创建会话工厂。它应该是一个单独的,并且是设计线程安全的。使用您提供的代码执行此操作的最简单方法是在openConnection()方法上使用synchronized关键字。但是,没有理由同步创建会话的代码部分并将其放在ThreadLocal实例上。粗略的解决方案将如下所示

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; 
     }
}