0

hibernate で遅延させるための 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 は静的変数なので??

4

1 に答える 1

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; 
     }
}
于 2013-01-29T09:47:08.087 に答える