1. 程式人生 > >如何理解Hibernate中的HibernateSessionFactory類

如何理解Hibernate中的HibernateSessionFactory類

package com.zz.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static org.hibernate.SessionFactory sessionFactory;
	
    private static Configuration configuration = new Configuration();
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    private static String configFile = CONFIG_FILE_LOCATION;

	static {
    	try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private HibernateSessionFactory() {
    }
	
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }

	/**
     *  Rebuild hibernate session factory
     *
     */
	public static void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	/**
     *  return session factory
     *
     */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
     *  return session factory
     *
     *	session factory will be rebuilded in the next call
     */
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}
	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}

HibernateSessionFactory類是自定義的SessionFactory,名字可以根據自己的喜好來決定。這裡用的是HibernateSessionFactory,其內容及解釋。上述程式碼是由myeclipse 自動生成的;也可以根據自己的情況寫出:

package com.zz.util;
 
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
//在使用hibernate開發專案,請一定保證只有一個SessionFactory
//一個數據庫對應一個SessionFactory 物件.
final public class MySessionFactory {
 
    private static SessionFactory sessionFactory=null;
     
    private MySessionFactory(){
         
    }
     
    static{
         
        sessionFactory =new Configuration().configure("com/zz/config/hsp.cfg.xml").buildSessionFactory(); 
        System.out.println("sessionFactory 型別"+sessionFactory);
    }
     
    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    }
     
}

Hibernate中,Session負責完成物件持久化操作。該檔案負責建立Session物件,以及關閉Session物件。從該檔案可以看出,Session物件的建立大致需要以下3個步驟:

① 初始化Hibernate配置管理類Configuration

② 通過Configuration類例項建立Session的工廠類SessionFactory

③ 通過SessionFactory得到Session例項。

³1. Configuration介面

Configuration負責管理Hibernate的配置資訊。Hibernate執行時需要一些底層實現的基本資訊。這些資訊包括:資料庫URL

、資料庫使用者名稱、資料庫使用者密碼、資料庫JDBC驅動類、資料庫dialect。用於對特定資料庫提供支援,其中包含了針對特定資料庫特性的實現,如Hibernate資料庫型別到特定資料庫資料型別的對映等。

使用Hibernate必須首先提供這些基礎資訊以完成初始化工作,為後續操作做好準備。這些屬性在Hibernate配置檔案hibernate.cfg.xml中加以設定,當呼叫:

Configuration config=new Configuration().configure();

時,Hibernate會自動在目錄下搜尋hibernate.cfg.xml檔案,並將其讀取到記憶體中作為後續操作的基礎配置。

³2. SessionFactory介面

SessionFactory負責建立Session例項,可以通過Configuration例項構建SessionFactory

Configuration config=new Configuration().configure();

SessionFactorysessionFactory=config.buildSessionFactory();

Configuration例項config會根據當前的資料庫配置資訊,構造SessionFacory例項並返回。SessionFactory一旦構造完畢,即被賦予特定的配置資訊。也就是說,之後config的任何變更將不會影響到已經建立的SessionFactory例項sessionFactory。如果需要使用基於變更後的config例項的SessionFactory,需要從config重新構建一個SessionFactory例項。

SessionFactory儲存了對應當前資料庫配置的所有對映關係,同時也負責維護當前的二級資料快取和Statement Pool。由此可見,SessionFactory的建立過程非常複雜、代價高昂。這也意味著,在系統設計中充分考慮到SessionFactory的重用策略。由於SessionFactory採用了執行緒安全的設計,可由多個執行緒併發呼叫。

³3. Session介面

SessionHibernate持久化操作的基礎,提供了眾多持久化方法,如saveupdatedelete等。通過這些方法,透明地完成物件的增加、刪除、修改、查詢等操作。

同時,值得注意的是,HibernateSession的設計是非執行緒安全的,即一個Session例項同時只可由一個執行緒使用。同一個Session例項的多執行緒併發呼叫將導致難以預知的錯誤。

Session例項由SessionFactory構建:

Configuration config=new Configuration().configure();

SessionFactorysessionFactory=config.buldSessionFactory();

Session session=sessionFactory.openSession();

³4. Transaction介面

TransactionHibernate中進行事務操作的介面,Transaction介面是對實際事務實現的一個抽象,這些實現包括JDBC的事務、JTA中的UserTransaction,甚至可以是CORBA事務。之所以這樣設計是可以讓開發者能夠使用一個統一的操作介面,使得自己的專案可以在不同的環境和容器之間方便地移值。事務物件通過Session建立。例如以下語句:

Transaction ts=session.beginTransaction();

³5. Query介面

Hibernate 2.x中,find()方法用於執行HQL語句。Hibernate 3.x廢除了find()方法,取而代之的是Query介面,它們都用於執行HQL語句。QueryHQL是分不開的。

Query query=session.createQuery(“fromtable where id=1”);

例如以下語句:

Query query=session.createQuery("fromtable whereid=?");

就要在後面設定其值:

Query.setString(0,"要設定的值");

上面的方法是通過“?”來設定引數,還可以用“:”後跟變數的方法來設定引數,如上例可以改為:

Query query=session.createQuery("fromtable whereid=:1");

Query.setString("kchValue","要設定的課程號值");

其使用方法是相同的,例如:

Query.setParameter(0,"要設定的值");

Query還有一個list()方法,用於取得一個List集合的示例,此示例中包括可能是一個Object集合,也可能是Object陣列集合。例如:

Query query=session.createQuery("fromtable whereid=1");

List list=query.list();