SessionFactory:
a) 用來產生和管理Session
b)通常情況下每個應用只需要一個SessionFactory
c)除非要訪問多個數據庫的情況
d) 關注兩個方法即: openSession 和 getCurrentSession
i. openSession 每次都是新的,需要close
ii. getCurrentSession 從上下文找,如果有,用舊的,如果沒有,建新的
1,用途,界定事務邊界
2,事務提交自動close
3,跟current_session_context_class (JTA、thread) 有關系
a)thread 使用 connection
注:上下文是什么?當前session運行的上下文,在hibernate.cfg.xml里指定的:
最常用的就是thread,看當前的線程里有沒有session對象,有了就拿,沒有就建新的。
<!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property>
SessionFactory怎么理解?
SessionFactory,產生session的工廠。一般情況下,每一個session里都有一個數據庫的連接,(如果沒有數據庫連接,怎么和數據庫打交道呢?)所以產生session的工廠里邊一定有好多個數據庫連接,所以SessionFactory維護的最重要的東西就是數據庫連接池。當它產生一個session的時候,他會從數據庫連接池拿出一個連接交給session。
package com.oracle.hibernate.id; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class HibernateCoreAPITest { private static SessionFactory sf = null; @BeforeClass public static void beforeClass() { //try-chatch是為了解決Junit有錯誤不提示的bug try { /** * AnnotationConfiguration().configure()會默認找src下的hibernate.cfg.xml,讀取配置信息。 * 最主要的是數據庫連接信息,幫你做出連接池。SessionFactory代表着跟數據庫的連接 * configure()有個重載方法configure(String url)可以指定文件名;如果配置文件叫hibernate.xml, * 就configure("hibernate.xml"),默認去classpath下找配置文件 */ sf = new AnnotationConfiguration().configure().buildSessionFactory(); } catch (HibernateException e) { e.printStackTrace(); } } @Test public void testTeacher() { Teacher t = new Teacher(); t.setName("li"); t.setTitle("high"); /** * getCurrentSession(): *1, 如果當前上下文有session,就拿來當前的session。如果沒有,就創建一個新的session * 2,不寫session.close(); * 注意:當session commit()提交的時候自動close(),寫了會報錯。 * 提交同時也會關閉當前session,上下文將不存在該session,此時getCurrentSession()就會創建一個新的session。 */ Session session = sf.getCurrentSession(); /** * session有個connection方法,返回值也是Connection,可以看出在這個session里綁定了一個Connection, * 這個Connection是從SessionFactory通過配置文件信息,產生的數據庫連接池里取出的。所以簡單理解,session等 * 同於一個Connection,不過也不能這個理解,hibernate還有很多很復雜的東西。 */ //session.connection(); //openSession(),永遠都打開新的session。需要close(); //Session session = sf.openSession(); session.beginTransaction(); session.save(t); //當當前的session提交了,就關閉了,對象就沒了。再getCurrentSession就是新的。 //session.getTransaction().commit(); //session.close(); //Session session2 = sf.openSession(); //兩次opSession不是一個session,返回false //System.out.println(session == session2); //Session session2 = sf.getCurrentSession(); //如果session沒commit,返回true,否則返回false //System.out.println(session == session2); } @AfterClass public static void afterClass() { sf.close(); } }