首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Hibernate 配置檔在單元測試中的彈性應用策略

     編輯:Java 相關知識

背景與問題

Hibernate 是主流 ORM 工具,單元測試與持續整合廣受重視。採用 Hibernate 的專案如何保證測試自動化與持續性?關鍵在於理解 Configuration 載入 hibernate.properties 與 hibernate.cfg.xml 的機制,並靈活運用其 API 切換配置。

本文以 Hibernate 2.1 為基礎,其他版本細節可能不同。

Configuration 載入流程

1. new Configuration()

  • 掃描 classpath 下的 hibernate.properties,存在則載入至 GLOBAL_PROPERTIES,否則列印 hibernate.properties not found。
  • 將系統屬性 System.getProperties() 合併至 GLOBAL_PROPERTIES。
  • 驗證屬性有效性,棄用參數會發出警告。

2. configure()

  • 預設尋找 classpath 下的 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 進階用法

1. 指定替代配置檔

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

2. 程式化設定屬性

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

常用方法:addProperties(Element/Properties)、setProperties(Properties)、setProperty(String, String)。可準備多組 .properties 針對不同測試場景切換。

3. 直接指定映射檔

繞過 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");

單元測試實戰範例

場景:測試 one-to-many 雙向關聯的 inverse 屬性

準備兩組映射檔: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 映射檔

優勢總結

  1. 按需載入映射檔:大型專案含大量 .hbm.xml,測試特定 PO 時無需載入全部,addClass/addFile 靈活高效。
  2. 多配置檔切換:學習/驗證不同特性(如 lazy、inverse)時,準備多組配置檔,程式碼不變,參數化傳入,避免手動改檔出錯。
  3. 自動化測試必要條件:持續整合過程無人工干預,不同測試案例需對應不同配置,setProperties/addFile 實現全自動化,保證持續性。

結語

掌握 Hibernate 配置載入順序與 API,善用多配置檔策略,能大幅提升測試效率,確保自動化與持續整合品質。持續集成的核心在於「自動化、持續性、無手工干預」,彈性配置管理是關鍵拼圖。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved