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();
        }
    
    
    }
  • 相关阅读:
    【转】浏览器的渲染:过程与原理
    DOMContentLoaded、ready、load事件的区别
    ES6中export default 与export区别
    require一个node模块什么时候需要加上.default
    【转】函数防抖与函数节流
    【转】JavaScript函数柯里化的一些思考
    【原】javascript笔记之splice和slice这两兄弟为毛这么难记
    【转】JS 的 new 到底是干什么的?
    【原】移动端vue页面点透事件
    【转】用 async/await 来处理异步
  • 原文地址:https://www.cnblogs.com/jepson6669/p/8487974.html
Copyright © 2011-2022 走看看