1
2
3
4
|
Configuration cfg = new Configuration(); cfg.addResource( "com/demo/hibernate/beans/User.hbm.xml" ); cfg.setProperty(System.getProperties()); SessionFactory sessionFactory = cfg.buildSessionFactory(); |
SessionFactory用到了一個設計模式 工廠模式 用戶程序從工程類SessionFactory取得Session實例 設計者的意圖就是讓它能在整個應用中共享 典型的來說 一個項目通常只需要一個SessionFactory就夠了 因此我們就設計了HibernateSessionFactory.java這個輔助類 定義了一個靜態的Configuration和SessionFactory對象
1
2
|
private static final Configuration cfg = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; |
這兩個對象對整個應用來說只有一個實例存在 因此為用戶的訪問定義一個本地線程變量:
1
|
private static final ThreadLocal threadLocal = new ThreadLocal(); |
該線程變量是靜態的 對每一個訪問該線程的用戶產生一個實例 這樣在要取得Session對象時 首先從當前用戶的線程中取得Session對象 如果還沒有創建 則從SessionFactory中創建一個Session 此時會判斷SessionFactory對象是否已經創建 該對象對這個應用來說 只有一個 因此 只有第一次訪問該變量的用戶才會創建該對象
HibernateSessionFactory.java 取得Session對象的過程如下表示
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public static Session currentSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null ) { if (sessionFactory == null ) { try { cfg.configure(CONFIG_FILE_LOCATION); sessionFactory = cfg.buildSessionFactory(); } catch (Exception e) { System.err.println( "%%%% Error Creating SessionFactory %%%%" ); e.printStackTrace(); } } session = sessionFactory.openSession(); threadLocal.set(session); } return session; } |
首先判斷threadLocal中是否存在Session對象 如果不存在 則創建Session對象 在創建Session對象時 首先要判斷系統是否已經加載Configuration 如果沒有sessionFactory 則需要先創建該對象 創建完成的Session對象 需要保存在threadLocal中以供本次訪問線程的下一次調用
在關閉Session對象是 只需要從當前線程中取得Session對象 關閉該對象 并置空本地線程變量即可
1
2
3
4
5
6
7
8
|
public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set( null ); if (session != null ) { session.close(); } } |
到此這篇關于Java Hibernate使用SessionFactory創建Session案例詳解的文章就介紹到這了,更多相關Java 使用SessionFactory創建Session內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:http://blog.chinaunix.net/uid-26284395-id-3049145.html