因爲SessionFactory是一個重量級的類,在一個應用中咱們須要作成單例的,我選擇的作法是: `java
import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; final public class Utils { private static SessionFactory sessionFactory=null; static{ //建立SessionFactory會話工廠 sessionFactory=new Configuration().configure().buildSessionFactory(); } private Utils(){ } public static SessionFactory geSessionFactory(){ return sessionFactory; } } `
這樣就能夠在須要的地方直接調用web
SessionFactory factory=Utils.geSessionFactory(); Session s1=factory.openSession(); Session s3=factory.getCurrentSession();
openSession()是打開一個Session,所以每次獲得的Session都不同session
getCurrentSession()是獲得當前線程的一個Session,在一個thread中使用該方法獲得的Session都是同一個Session 可是在使用getCurrentSession()前須要在hibernate.cfg.xml中作以下配置:ui
<!-- java程序 --> <property name="current_session_context_class">thread</property> <!-- web程序 --> <property name="current_session_context_class">jta</property>
不然會報以下錯誤: No CurrentSessionContext configured!
在使用getCurrentSession()獲得的session作查詢操做(load())時須要使用事務,不然 會報以下錯誤:hibernate
Exception in thread "main" org.hibernate.HibernateException: load is not valid without active transaction
並且這個session是自動關閉的線程
使用load()查詢時,若是查詢不到,則會返回null, load()使用一種代理機制,若是不使用查詢獲得的對象,則不會執行SQL語句,只有使用對象時纔會執行SQL語句 【懶加載】 get()查詢,若是查詢不到,則會拋出異常,且在查詢時就執行SQL語句,無論查詢的結果會不會使用