java - 在Hql-Initialization中创建sessionFactory

标签 java hibernate static thread-safety sessionfactory

我已经创建了一个用于处理 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 是静态变量??

最佳答案

您不希望多个线程创建 session 工厂。它应该是单例,并且设计上是线程安全的。使用您提供的代码执行此操作的最简单方法是在 openConnection() 方法上使用同步关键字。但是,没有理由同步创建 session 并将其也放在 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; 
     }
}

关于java - 在Hql-Initialization中创建sessionFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14579380/

相关文章:

python - 如何指向django中的静态文件夹

c++ - 将 Cpp 转换为 Rust,处理全局静态对象

java - 在 Java 中将二维整数数组显示为图像

java - 在java中使用正则表达式从基于下划线的字符串中获取子字符串

java - hibernate 刷新方法

java - 使用 Hibernate 的 Spring Boot 在使用 H2 数据库启动时生成丢弃约束错误

java - Spring Boot + Hibernate JPA 延迟获取模式仍然查询实体中的列表

java - 如何将使用 'this' 的语句声明为静态?

java - System.getenv(/**vName**/) 和 Autowiring 环境之间的区别和执行environment.getProperty ("myProp");

java - 如何对方法调用返回的对象的结构进行单元测试?