1. 程式人生 > >hibernate之SessionFactory和Session

hibernate之SessionFactory和Session

1. 關於SessionFactory

1.) SessionFactory是一個與連線池的類差不多的東西,在這裡存著多個Session—與資料庫的會話(相當於connection)

2.) 因為連線資料庫的配置資訊和對映資訊都在SessionFactory,比較佔記憶體,所以在hibernate中SessionFactory只有一個

3.) SessionFactory是執行緒安全的

2. 關於Session類
1.) session.getTransaction().commit();之後, 就會被銷燬
2.) session裡面除了有connection之外,還有...
3.) session的作用就是對資料庫進行增刪改查
4.) session生命週期很短,session.close() 一關閉,該物件就沒有了
5.) session物件是執行緒不安全的

3. getCurrentSession和getSession的區別

1.) sessionFactory.openSession(); 打一個新的session(Connection)即一個與為資料庫的會話

2.) 必須要配置:current_session_context_class=thread

/**
 * 此類負責建立SessionFactory,此類,一個應用程式只有一個,且是執行緒安全的
 * SessionFactory相當於資料庫連線池,  Session相當於connection
 */
public class HibernateUtils {
	private static SessionFactory sessionFactory;    //宣告會話工廠(session(用完後即死亡),connection)
	static{
		try{
			Configuration conf = new Configuration();//宣告讀取配置檔案的類,此類在例項化時預設即讀取
            // 預設會先去讀取classpath下的hibernate.properties,然後讀取hibernate.cfg.xml檔案,後者會覆蓋前者
			conf.configure();	 
			sessionFactory = conf.buildSessionFactory();	//建立會話工廠
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public static SessionFactory getSessionFactory(){		//返回會話的工廠
		return sessionFactory;
	}
	public static Session getSession(){			//從工廠開啟一個新的Session並返回
		return sessionFactory.openSession();
	}
}