淺析Hibernate加載配置文件
在向大家詳細介紹Hibernate加載配置文件之前,首先讓大家了解下使用Hibernate的經驗,然后全面介紹Hibernate加載配置文件。
Hibernate是一個流行的開源對象關系映射工具,單元測試和持續集成的重要性也得到了廣泛的推廣和認同,在采用了Hibernate的項目中如何保證測試的自動化和持續性呢?本文討論了Hibernate加載配置文件Hibernate.properties和Hibernate.cfg.xml的過程,以及怎么樣將Hibernate提供的配置文件的訪問方法靈活運用到單元測試中。
注意:本文以Hibernate2.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。
- }
- }
以上介紹Hibernate加載配置文件。
【編輯推薦】