spring-5.1.8 + hibernate-5.4.3通過HibernateUtil創建sessionFactory

代碼:

package com.demo.hibernate;
 
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
 
public class HibernateUtil {
	//爲保證線程安全,將Seeeion放到ThreadLocal中管理。這樣就避免了Session的多線程共享數據的問題
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static SessionFactory sessionFactory = null;//SessionFactory對象
    //靜態塊(在類被加載時執行,且生命週期內只執行一次)
	static {
    	try {
    		// 加載Hibernate配置文件,默認爲hibernate.cfg.xml
			Configuration cfg = new Configuration().configure();
			//	創建會話工廠
			//	hibernate4.0版本前這樣獲取sessionFactory = configuration.buildSessionFactory();
			//	hibernate5以後規定,所有的配置或服務,要生效,必須配置或服務註冊到一個服務註冊類(服務構建器-->服務註冊器)
			ServiceRegistry serviceRegistry = cfg.getStandardServiceRegistryBuilder().build();
			//  根據服務註冊類創建一個元數據資源集,同時構建元數據並生成應用一般唯一的的session工廠
			sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
		} catch (Exception e) {
			System.err.println("1:創建會話工廠失敗");
			e.printStackTrace();
		}
    }
	/**
     *	獲取Session
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();	//獲取ThreadLocal中當前線程共享變量的值。
		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {		//如果會話工廠創建失敗爲空就在重新創建一次
				rebuildSessionFactory();
			}
			//創建Sqlsession數據庫會話
			session = (sessionFactory != null) ? sessionFactory.openSession(): null;
			//設置ThreadLocal中當前線程共享變量的值。
			threadLocal.set(session);
		}
 
        return session;
    }
	/**
     * 重建會話工廠
     */
	public static void rebuildSessionFactory() {
    	try {
    		// 加載Hibernate配置文件
			Configuration cfg = new Configuration().configure();
			//	創建會話工廠
			//	hibernate4.0版本前這樣獲取sessionFactory = configuration.buildSessionFactory();
			//	hibernate5以後規定,所有的配置或服務,要生效,必須配置或服務註冊到一個服務註冊類(服務構建器-->服務註冊器)
			ServiceRegistry serviceRegistry = cfg.getStandardServiceRegistryBuilder().build();
			//  根據服務註冊類創建一個元數據資源集,同時構建元數據並生成應用一般唯一的的session工廠
			sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
		} catch (Exception e) {
			System.err.println("2:創建會話工廠失敗");
			e.printStackTrace();
		}
	}
	/**
	 * 獲取SessionFactory對象
	 * @return SessionFactory對象
	 */
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	/** 
     *	關閉Session
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        //使用set(null)來回收ThreadLocal設置的值.
        threadLocal.set(null);
        if (session != null) {
            session.close();//關閉Session
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章