ITeye博客

封装HibernateUtil对象,方便的工具类(转)

/ty瑞克 · 2010-09-14 16:41 · hibernate · 企业架构 · Markdown

  1. package org.cric.util;
  2. import org.hibernate.Session;
  3. import org.hibernate.SessionFactory;
  4. import org.hibernate.cfg.Configuration;
  5. public class HibernateUtil {
  6. private static SessionFactory factory;
  7. static{//只创建一次,单实例
  8. try{
  9. //实例化Configuration对象,configure()方法,默认加载hibernate.hbm.xml文件
  10. Configuration cfg=new Configuration().configure();
  11. //虚拟数据库
  12. factory=cfg.buildSessionFactory();
  13. }catch(Exception e){
  14. e.printStackTrace();
  15. }
  16. }
  17. public static SessionFactory getSessionFactory(){//获取SessionFactory对象
  18. return factory;
  19. }
  20. public static Session getSession(){//获取Session对象
  21. return factory.openSession();
  22. }
  23. public static void closeSession(Session session){//关闭Session,因为Session不是线程安全的!
  24. //线程安全是指多个线程并发时,线程之间不会相互影响
  25. //比如,在多个线程同时操作对象的某个实例变量时,就回出现不正确的现象
  26. if(session!=null){
  27. if(session.isOpen()){
  28. session.close();
  29. }
  30. }
  31. }
  32. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。