官方文檔常用 hibernate.properties 或 hibernate.cfg.xml 放在 classpath 根目錄,實際上名稱、位置均可自定,多資料庫環境下可擁有多個配置文件。創建 SessionFactory 時指定:
protected static String CONFIG_FILE = "my_hibernate.config";
String configPath = System.getProperty("my.config");
sessionFactory = new Configuration()
.configure(new File(configPath + File.separator + CONFIG_FILE))
.buildSessionFactory();
官方建議一表一映射文件,但在小型專案、維護人員少時,可合併為一或幾個文件。建議按邏輯模組劃分,每人維護一個。
<!-- 大型專案分散映射 -->
<mapping resource="com/hongsoft/test/persistence/Cat.hbm.xml"/>
<mapping resource="com/hongsoft/test/persistence/Animal.hbm.xml"/>
<!-- 小型專案集中映射 -->
<mapping resource="res_hibernate_map.xml"/>
注意:映射文件路徑只能用相對路徑,以 classes 根目錄為基準。
啟動檢查時,系統依據映射文件驗證 PO 類:
name 對應 getName()/setName())利用此特性可在 PO 中加入表單驗證屬性(如 updatedPasswd),構造 FormBean 或 ValueObject,但需權衡耦合度。
三大定則揭示 Hibernate 映射配置的靈活性與檢查機制,助力開發者避開常見誤區,根據專案規模選擇適當映射組織策略。