本文介紹 Hibernate 3 兩大進階特性:Interceptor 介面 實現持久化生命週期攔截,以及 SchemaExport 工具 從映射文件自動建立資料庫表結構。
實作 org.hibernate.Interceptor 可在 Session 操作前後注入自定義邏輯。核心回調方法:
| 方法 | 觸發時機 | 返回值/作用 |
|---|---|---|
onLoad | 載入物件前 | boolean:true/拋出異常阻止載入 |
onSave | 儲存物件前 | boolean:阻止儲存 |
onUpdate / onFlushDirty | 更新/髒檢查時 | boolean/修改狀態數組 |
onDelete | 刪除物件前 | void |
preFlush / postFlush | Flush 前/後 | void:批次處理 |
findDirty | 髒屬性檢測 | int[]:返回髒屬性索引,null 走預設 |
instantiate | 實例化實體 | Object:自定義構造,null 用預設 |
isTransient | 判斷瞬時態 | Boolean |
getEntityName / getEntity | 元數據訪問 | String/Object |
| 事務回調 | afterTransactionBegin、beforeTransactionCompletion、afterTransactionCompletion | void |
public class AuditInterceptor implements Interceptor {
public boolean onSave(Object entity, Serializable id, Object[] state, String[] names, Type[] types) {
if (entity instanceof Auditable) {
// 自動填入創建時間、操作人
return true; // 表示已修改 state 數組
}
return false;
}
// ... 其他回調
}
// 開啟 Session 時注入
Session session = sessionFactory.openSession(new AuditInterceptor());
應用場景:審計日誌、自動時間戳、軟刪除標記、自定義髒檢查、實例化策略控制。
利用 org.hibernate.tool.hbm2ddl.SchemaExport 讀取 hibernate.cfg.xml 中映射文件,自動生成建表 SQL 並執行。
hibernate.cfg.xml 需配妥 JDBC、Dialect、映射文件引用:
<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/demo</property>
<mapping resource="onlyfun/caterpillar/User.hbm.xml"/>
映射文件 User.hbm.xml:
<class name="onlyfun.caterpillar.User" table="user">
<id name="id" column="id"><generator class="native"/></id>
<property name="name" column="name"/>
<property name="age" column="age"/>
</class>
public class HbmToTable {
public static void main(String[] args) {
Configuration cfg = new Configuration().configure();
SchemaExport export = new SchemaExport(cfg);
export.create(true, true); // 輸出 SQL 到控制台、執行建表
}
}
Creating tables...
Hibernate: drop table if exists user
Hibernate: create table user (
id integer not null auto_increment,
name varchar(255),
age integer,
primary key (id)
)
schema export complete
資料庫實際建表結構與映射定義一致。