您的位置:軟件測試 > 開源軟件測試 > 開源功能測試工具 >
Hibernate配置文件在單元測試中的靈活運用
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時間:[ 2012/11/29 13:35:31 ] 推薦標(biāo)簽:

3.3. configure()在做什么?
new Configuration()討論至此,下面討論configure()方法。

configure()方法默認(rèn)會在classpath下面尋找hibernate.cfg.xml文件,如果沒有找到該文件,系統(tǒng)會打印如下信息并拋出HibernateException異常。

 

hibernate.cfg.xml not found

如果找到該文件,configure()方法會首先訪問< session-factory >,并獲取該元素的name屬性,如果非空,將用這個配置的值來覆蓋hibernate.properties的hibernate.session_factory_name的配置的值,從這里我們可以看出,hibernate.cfg.xml里面的配置信息可以覆蓋hibernate.properties的配置信息。

接著configure()方法訪問<session-factory>的子元素,首先將使用所有的<property>元素配置的信息(注2),如前面我們使用的配置文件

 

<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>

會覆蓋hibernate.properties里面對應(yīng)的配置,hibernate2.1發(fā)布包里面自帶的hibernate.properties文件(位于%HIBERNATE_HOME%/etc下面)里面的值,如下:

 

hibernate.dialect net.sf.hibernate.dialect.HSQLDialect
hibernate.connection.driver_class org.hsqldb.jdbcDriver
hibernate.connection.username sa
hibernate.connection.password
hibernate.connection.url jdbc:hsqldb:hsql://localhost

然后configure()會順序訪問以下幾個元素的內(nèi)容

 

<mapping>
<jcs-class-cache>
<jcs-collection-cache>
<collection-cache>

其中<mapping>是必不可少的,必須通過配置<mapping>,configure()才能訪問到我們定義的java對象和關(guān)系數(shù)據(jù)庫表的映射文件(hbm.xml),例如:

 

<mapping resource="Cat.hbm.xml"/>

通過以上的分析,我們對hibernate配置文件hibernate.properties和hibernate.cfg.xml的默認(rèn)的加載過程比較清楚了。

3.4 Configuration的其他用法
Configuration的configure ()方法還支持帶參數(shù)的訪問方式,你可以指定hbm.xml文件的位置,而不是使用默認(rèn)的classpath下面的hibernate.cfg.xml這種方式,例如:

 

Configuration cfg = new Configuration().configure("myexample.xml");

同時Configuration還提供了一系列方法用來定制hibernate的加載配置文件的過程,讓你的應(yīng)用更加靈活,常用的是以下幾種:

 

addProperties(Element)
addProperties(Properties)
setProperties(Properties)
setProperty(String, String)

通過以上幾個方法,除了使用默認(rèn)的hibernate.properties文件,你還可以提供多個.properties配置文件,使用Hibernate的時候根據(jù)不同的情況使用不同的配置文件,例如:

 

Properties properties = Properties.load("my.properties");
Configuration config = new Configuration().setProperties(properties).configure();

上一頁123下一頁
軟件測試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd