zoukankan      html  css  js  c++  java
  • hibernateUtil

    package cn.itcast.crm.util;
    
    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>
     * 
     */
    public class HibernateUtil {
    
    	// 会话工厂,以单例方式管理
    	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();
    	}
    
    
    }
    

      

  • 相关阅读:
    位运算的应用
    MySql的自增主键以及TEXT数据类型使用
    MaxDos启动盘拆解
    QT预备式(包含MySql配置)未完成……
    关于Services.exe开机CPU内存使用暴增解决方案
    Windows Upnp 服务补丁——UpnpFix V1.0
    Memory Ordering
    "FoxitReaderOCX.ocx failed to load" 问题解决方案
    LameDropXPd V2.0 (L.A.M.E 3.97) 完美汉化版
    编译QT的MySql驱动问题及解决方案
  • 原文地址:https://www.cnblogs.com/wuxu/p/11000280.html
Copyright © 2011-2022 走看看