淺析Hibernate加載配置文件
在向大家詳細(xì)介紹Hibernate加載配置文件之前,首先讓大家了解下使用Hibernate的經(jīng)驗(yàn),然后全面介紹Hibernate加載配置文件。
Hibernate是一個(gè)流行的開源對象關(guān)系映射工具,單元測試和持續(xù)集成的重要性也得到了廣泛的推廣和認(rèn)同,在采用了Hibernate的項(xiàng)目中如何保證測試的自動(dòng)化和持續(xù)性呢?本文討論了Hibernate加載配置文件Hibernate.properties和Hibernate.cfg.xml的過程,以及怎么樣將Hibernate提供的配置文件的訪問方法靈活運(yùn)用到單元測試中。
注意:本文以Hibernate2.1作為討論的基礎(chǔ),不保證本文的觀點(diǎn)適合于其他版本。
對于Hibernate的初學(xué)者來說,***次使用Hibernate的經(jīng)驗(yàn)通常是:
1.安裝配置好Hibernate,我們后面將%Hibernate_HOME%作為對Hibernate安裝目錄的引用,
2.開始創(chuàng)建好自己的***個(gè)例子,例如Hibernate手冊里面的類Cat,
3.配置好hbm映射文件(例如Cat.hbm.xml,本文不討論這個(gè)文件內(nèi)配置項(xiàng)的含義)和數(shù)據(jù)庫(如hsqldb),
4.在項(xiàng)目的classpath路徑下添加一個(gè)Hibernate.cfg.xml文件,如下(***次使用Hibernate最常見的配置內(nèi)容):
- <?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.然后還需要提供一個(gè)類來測試一下創(chuàng)建,更新,刪除和查詢Cat,對于熟悉JUnit的開發(fā)人員,可以創(chuàng)建一個(gè)單元測試類來進(jìn)行測試,如下:
- 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();
- //注意這一行,這是本文重點(diǎn)討論研究的地方。
- session = cfg.buildSessionFactory().openSession();
- tx = session.beginTransaction();
- }
- protected void tearDown() throws Exception {
- tx.commit();
- session.close();
- }
- public void testCreate() {
- //請?jiān)诖朔椒▋?nèi)添加相關(guān)的代碼,本文不討論怎么樣使用Hibernate API。
- }
- public void testUpdate() {
- //請?jiān)诖朔椒▋?nèi)添加相關(guān)的代碼,本文不討論怎么樣使用Hibernate API。
- }
- public void testDelete() {
- //請?jiān)诖朔椒▋?nèi)添加相關(guān)的代碼,本文不討論怎么樣使用Hibernate API。
- }
- public void testQuery() {
- //請?jiān)诖朔椒▋?nèi)添加相關(guān)的代碼,本文不討論怎么樣使用Hibernate API。
- }
- }
以上介紹Hibernate加載配置文件。
【編輯推薦】