編寫HibernateUtil工具類去初始化hibernate

package vince;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
 * 用Configuration產生SessionFactory的代碼是非常耗時的
 * 我們希望它只執行一次
 * 因此做這個工具類來初始化hibernate
 * 由於工具類一般不希望被繼承
 * 用final
 * @author Vincent
 * @version 1.0
 */
public final class HibernateUtil {
	public static final SessionFactory sessionFactory;
	static
	{
		try
		{
			//採用默認的hibernate.cfg.xml來啓動一個Configuration的實例
			Configuration configuration=new Configuration().configure();
			//由Configuration的實例來創建一個SessionFactory實例
			sessionFactory=configuration.buildSessionFactory();
		}
		catch(Throwable ex)
		{
			System.err.println("Initial SessionFaction creation failed."+ex);
			throw new ExceptionInInitializerError(ex);
		}
	}
	//ThreadLocal可以隔離多個線程的數據共享,因此不再需要對線程同步
	public static final ThreadLocal<Session> session
	    =new ThreadLocal<Session>();
	public static Session getSession() throws HibernateException
	{
		Session s=session.get();
		//如果該線程還沒有Session,則創建一個新的Session
		if(s==null)
		{
			s=sessionFactory.openSession();
			//將獲得的Session存儲在ThreadLocal變量session裏
			session.set(s);
		}
		return s;	
	}
	public static void closeSession() throws HibernateException
	{
		Session s=session.get();
		if(s!=null)
			s.close();
		session.set(null);
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章