Hibernate 是一個流行的開源對象關系映射工具,單元測試和持續集成的重要性也得到了廣泛的推廣和認同,在采用了Hibernate的項目中如何保證測試的自動化和持續性呢?本文討論了Hibernate加載其配置文件hibernate.properties和hibernate.cfg.xml的過程,以及怎么樣將hibernate提供的配置文件的訪問方法靈活運用到單元測試中。
1 介紹
Hibernate 是一個流行的開源對象關系映射工具,單元測試和持續集成的重要性也得到了廣泛的推廣和認同,在采用了Hibernate的項目中如何保證測試的自動化和持續性呢?本文討論了Hibernate加載其配置文件hibernate.properties和hibernate.cfg.xml的過程,以及怎么樣將hibernate提供的配置文件的訪問方法靈活運用到單元測試中。注意:本文以hibernate2.1作為討論的基礎,不保證本文的觀點適合于其他版本。
2 讀者
Java開發人員,要求熟悉JUnit和掌握Hibernate的基礎知識
3 內容
3.1.準備
對于hibernate的初學者來說,第一次使用hibernate的經驗通常是:
1, 安裝配置好Hibernate,我們后面將%HIBERNATE_HOME%作為對Hibernate安裝目錄的引用,
2, 開始創建好自己的第一個例子,例如hibernate手冊里面的類Cat,
3, 配置好hbm映射文件(例如Cat.hbm.xml,本文不討論這個文件內配置項的含義)和數據庫(如hsqldb),
4, 在項目的classpath路徑下添加一個hibernate.cfg.xml文件,如下(第一次使用hibernate常見的配置內容):
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<property name="dialect">net.sf.hibernate.dialect.HSQLDialect</property>
<property name="hibernate.show_sql">false</property>
<mapping resource="Cat.hbm.xml"/>
</session-factory>
</hibernate-configuration>
5, 然后還需要提供一個類來測試一下創建,更新,刪除和查詢Cat,對于熟悉JUnit的開發人員,可以創建一個單元測試類來進行測試,如下:
import junit.framework.TestCase;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;
public class CatTest extends TestCase {
private Session session;
private Transaction tx;
protected void setUp() throws Exception {
Configuration cfg = new Configuration().configure();////注意這一行,這是本文重點討論研究的地方。
session = cfg.buildSessionFactory().openSession();
tx = session.beginTransaction();
}
protected void tearDown() throws Exception {
tx.commit();
session.close();
}
public void testCreate() {
//請在此方法內添加相關的代碼,本文不討論怎么樣使用Hibernate API。
}
public void testUpdate() {
//請在此方法內添加相關的代碼,本文不討論怎么樣使用Hibernate API。
}
public void testDelete() {
//請在此方法內添加相關的代碼,本文不討論怎么樣使用Hibernate API。
}
public void testQuery() {
//請在此方法內添加相關的代碼,本文不討論怎么樣使用Hibernate API。
}
}
3.2 new Configuration()都做了什么?
對于第一次使用hibernate的新手來說,下面的這段代碼可以說是常見的使用Configuration方式。
Configuration cfg = new Configuration().configure();
Configuration是hibernate的入口,在新建一個Configuration的實例的時候,hibernate會在classpath里面查找hibernate.properties文件,如果該文件存在,則將該文件的內容加載到一個Properties的實例GLOBAL_PROPERTIES里面,如果不存在,將打印信息
hibernate.properties not found
然后是將所有系統環境變量(System.getProperties())也添加到GLOBAL_PROPERTIES里面(注1)。如果hibernate.properties文件存在,系統還會驗證一下這個文件配置的有效性,對于一些已經不支持的配置參數,系統將打印警告信息。