Hibernate 核心配置涉及三類文件,優先級遞減:
此外,可通過代碼指定任意配置文件路徑:`new Configuration().configure(file)`
啟動日誌揭示真相:
1. 尋找 hibernate.properties (未找到) 2. 初始化位元組碼增強器 (cglib) 3. 初始化時間戳服務 4. 讀取 hibernate.cfg.xml 5. 加載映射文件/類
驗證實驗: 將 `hibernate.cfg.xml` 改名為 `.bak`,放置同內容的 `hibernate.properties`,程序正常運行,日誌顯示直接讀取屬性文件。
hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.connection.driver_class=com.mysql.jdbc.Driver hibernate.connection.url=jdbc:mysql://localhost:3306/jdbc hibernate.connection.username=root hibernate.connection.password=123123 hibernate.current_session_context_class=thread hibernate.show_sql=true hibernate.format_sql=true
注意: 無法在 properties 中引用映射文件,需代碼手動 `addResource()`。
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"https://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 數據庫連接 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/jdbc</property>
<property name="connection.username">root</property>
<property name="connection.password">123123</property>
<!-- 連接池 (內建/外部) -->
<property name="connection.pool_size">10</property>
<!-- property name="hibernate.c3p0.min_size">5</property -->
<!-- 運行行為 -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property> <!-- auto/create/update/validate -->
<property name="current_session_context_class">thread</property>
<!-- 映射文件引用 -->
<mapping resource="edu/fjnu/hotelsys/domain/Hotel.hbm.xml"/>
<mapping resource="edu/fjnu/hotelsys/domain/Room.hbm.xml"/>
<!-- 亦可掃描包: mapping package="..." -->
</session-factory>
</hibernate-configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"https://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="edu.fjnu.hotelsys.domain">
<class name="Room" table="room">
<id name="roomId" column="room_id" type="java.lang.Integer">
<generator class="increment"/> <!-- 主鍵生成策略 -->
</id>
<property name="roomNo" column="room_no" type="string" length="10" not-null="true"/>
<property name="roomType" column="room_type" type="string" length="1" not-null="true"/>
<property name="roomStatus" column="room_status" type="string" length="1" not-null="true"/>
<property name="roomMemo" column="room_memo" type="string" length="200"/>
<property name="roomEquipStr" column="room_equip" type="string" length="20"/>
<many-to-one name="hotel" class="Hotel" column="hotel_no" fetch="join"/> <!-- 多對一關聯 -->
</class>
</hibernate-mapping>
關鍵元素:
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // 默認讀取 hibernate.cfg.xml
.build();
return new MetadataSources(registry)
.buildMetadata()
.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() { return sessionFactory; }
public static void shutdown() { getSessionFactory().close(); }
}
AnnotationConfiguration cfg = new AnnotationConfiguration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Hotel.class)
.addAnnotatedClass(Room.class);
SessionFactory sf = cfg.buildSessionFactory();
| 類/方法 | 作用 | 關鍵點 |
|---|---|---|
| Configuration | 配置管理入口,解析配置與映射 | 單例模式,構建 SessionFactory 後即可丟棄 |
| configure() | 讀取默認 hibernate.cfg.xml | 可傳入 File/URL 指定自定義配置文件 |
| addResource() | 加載 .hbm.xml 映射文件 | 路徑相對 classpath |
| addClass() | 加載註解實體類 | 需 AnnotationConfiguration |
| setProperty() | 程序化覆蓋/新增屬性 | 屬性名參考 org.hibernate.cfg.Environment 常量 |
| buildSessionFactory() | 構建 SessionFactory,鎖定配置 | 重量級操作,**全應用僅需一個** (多數據庫除外) |
| SessionFactory | 線程安全、不可變、內含二級快取/連接池/編譯 SQL | 工廠模式,代理數據存儲源 |
Hibernate 配置看似繁雜,實則遵循「約定優於配置」原則。掌握配置加載順序、核心屬性含義、映射元素語義、SessionFactory 生命週期管理,即可駕馭從簡單 CRUD 到複雜關聯查詢的各類持久化場景。