Hibernate 是主流 ORM 工具,單元測試與持續整合廣受重視。採用 Hibernate 的專案如何保證測試自動化與持續性?關鍵在於理解 Configuration 載入 hibernate.properties 與 hibernate.cfg.xml 的機制,並靈活運用其 API 切換配置。
本文以 Hibernate 2.1 為基礎,其他版本細節可能不同。
hibernate.properties,存在則載入至 GLOBAL_PROPERTIES,否則列印 hibernate.properties not found。System.getProperties() 合併至 GLOBAL_PROPERTIES。hibernate.cfg.xml,找不到拋 HibernateException。<session-factory> 的 name 屬性覆蓋 hibernate.session_factory_name。<property> 子元素,覆蓋 hibernate.properties 同名設定(如連線資訊、方言)。<mapping>、<jcs-class-cache> 等元素,<mapping> 為必須,指定 .hbm.xml 映射檔。結論: hibernate.cfg.xml 設定優先級高於 hibernate.properties。
Configuration cfg = new Configuration().configure("myexample.xml");
Properties props = Properties.load("my.properties");
Configuration cfg = new Configuration().setProperties(props).configure();
常用方法:addProperties(Element/Properties)、setProperties(Properties)、setProperty(String, String)。可準備多組 .properties 針對不同測試場景切換。
繞過 hibernate.cfg.xml 的 <mapping>,直接載入 .hbm.xml:
// 方式一:透過 Class 自動推導路徑
Configuration cfg = new Configuration().addClass(Cat.class);
// 方式二:透過 URL
Configuration cfg = new Configuration().addURL(Configuration.class.getResource("Cat.hbm.xml"));
// 方式三:透過檔案路徑
Configuration cfg = new Configuration().addFile("Cat.hbm.xml");
準備兩組映射檔:bidirect.inverse.false.hbm.xml 與 bidirect.inverse.true.hbm.xml。撰寫兩個測試類別,各自在 setUp() 載入對應映射檔:
// FalseInverseTest.java
public class FalseInverseTest extends TestCase {
private Session session; private Transaction tx;
protected void setUp() throws Exception {
Configuration cfg = new Configuration().addFile("bidirect.inverse.false.hbm.xml");
session = cfg.buildSessionFactory().openSession();
tx = session.beginTransaction();
}
protected void tearDown() throws Exception { tx.commit(); session.close(); }
public void testLogic() { /* 測試碼 */ }
}
// TrueInverseTest.java 同理,載入 inverse.true 映射檔
.hbm.xml,測試特定 PO 時無需載入全部,addClass/addFile 靈活高效。setProperties/addFile 實現全自動化,保證持續性。掌握 Hibernate 配置載入順序與 API,善用多配置檔策略,能大幅提升測試效率,確保自動化與持續整合品質。持續集成的核心在於「自動化、持續性、無手工干預」,彈性配置管理是關鍵拼圖。