hibernate初始化优化

 还记得每个hibernate初学者都会被指导使用这样的函数来获取数据库资源 
  1. public   static   Session   currentSession()   throws   HibernateException   { 
  2.         Session   session   =   (Session)   threadLocal.get(); 
  3.         if   (session   ==   null)   { 
  4.             if   (sessionFactory   ==   null)   { 
  5.                 try   { 
  6.                     cfg.configure(CONFIG_FILE_LOCATION); 
  7.                     sessionFactory   =   cfg.buildSessionFactory(); 
  8.                 } 
  9.                 catch   (Exception   e)   { 
  10.                     System.err.println("%%%%   Error   Creating   SessionFactory   %%%%"); 
  11.                     e.printStackTrace(); 
  12.                 } 
  13.             } 
  14.             session   =   sessionFactory.openSession(); 
  15.             threadLocal.set(session); 
  16.         } 
  17.         return   session; 
  18.     } 

当你打开TOmcat的时候,一下有几十人来访问你的页面,那么这个函数很有可能就会初始化失败了。多年前实践中总结出来,修改一下,今天想到在这里写一下: 
  
  1.   public static Session currentSession() throws HibernateException { 
  2.         Session session = (Session) threadLocal.get(); 
  3.         if (session == null) { 
  4.             if (sessionFactory == null) { 
  5.                 synchronized(SessionFactory.class){ 
  6.                     if (sessionFactory == null) { 
  7.                         try { 
  8.                             cfg.configure(CONFIG_FILE_LOCATION); 
  9.                             sessionFactory = cfg.buildSessionFactory(); 
  10.                         } 
  11.                         catch (Exception e) { 
  12.                             System.err.println("%%%% Error Creating SessionFactory %%%%"); 
  13.                             e.printStackTrace(); 
  14.                         } 
  15.                     } 
  16.                 } 
  17.             } 
  18.             session = sessionFactory.openSession(); 
  19.             threadLocal.set(session); 
  20.         } 
  21.         return session; 
  22.     } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值