zoukankan      html  css  js  c++  java
  • 016-hibernateutils模板

    package ${enclosing_package};
    
    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    /**
     * 
     * <p>
     * Title: HibernateUtil
     * </p>
     * <p>
     * Description:session工具类
     * </p>
     * <p>
     * Company: www.itcast.com
     * </p>
     * 
     * @author 传智.燕青
     * @date 2016年2月2日
     * @version 1.0
     */
    public class ${primary_type_name} {
    
        // 会话工厂,以单例方式管理
        private static SessionFactory sessionFactory;
    
        // ThreadLocal存储session
        private static ThreadLocal<Session> session = new ThreadLocal<Session>();
    
    
        // 以单例方式管理sessionFactory
        static {
            try {
                sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
            } catch (HibernateException e) {
                e.printStackTrace();
                throw new HibernateException("初始化会话工厂失败!");
            }
    
        }
        //得到一个单例的会话工厂
        public static SessionFactory getSessionFactory(){
            return sessionFactory;
        }
        //获取一个新session
        public static Session openSession(){
            return sessionFactory.openSession();
        }
        
        //获取当前与线程绑定的session,如果获取不到则创建一个新session并与当前线程绑定
    //    public static Session getCurrentSession() throws HibernateException {
    //        //获取当前线程绑定的session
    //        Session s = (Session) session.get();
    //        if (s == null) {
    //            //创建一个新session
    //            s = sessionFactory.openSession();
    //            //新session并与当前线程绑定
    //            session.set(s);
    //        }
    //        return s;
    //    }
     
        public static Session getCurrentSession() throws HibernateException {
            return sessionFactory.getCurrentSession(); 
        }
        //关闭当前线程绑定的session
    //    public static void closeSession() throws HibernateException {
    //        //获取当前线程绑定的session
    //        Session s = (Session) session.get();
    //        if (s != null){
    //            //关闭session
    //            s.close(); 
    //        }
    //        session.set(null);
    //    }
        
        public static void closeSession() throws HibernateException {
            sessionFactory.getCurrentSession().close();
        }
    
    
    }
  • 相关阅读:
    VS2010 VC Project的default Include设置
    Linux 下的编辑/编译器
    用命令实现Win7远程桌面关机和重启
    怎样快速刪除Word中超链接?
    chrome浏览器世界之窗浏览器的收藏夹在哪?
    代码量查找工具[最好用的]
    C项目实践--网络协议和套接字编程
    memmove 和 memcopy
    bzoj2456: mode
    bzoj1205: [HNOI2005]星际贸易
  • 原文地址:https://www.cnblogs.com/jepson6669/p/8487974.html
Copyright © 2011-2022 走看看