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

Hibernate 3 進階特性 (二):Interceptor 回調機制與 SchemaExport 從映射文件正向生成資料表

     編輯:Java 相關知識

本文介紹 Hibernate 3 兩大進階特性:Interceptor 介面 實現持久化生命週期攔截,以及 SchemaExport 工具 從映射文件自動建立資料庫表結構。

Interceptor 介面:深入持久化生命週期

實作 org.hibernate.Interceptor 可在 Session 操作前後注入自定義邏輯。核心回調方法:

方法觸發時機返回值/作用
onLoad載入物件前boolean:true/拋出異常阻止載入
onSave儲存物件前boolean:阻止儲存
onUpdate / onFlushDirty更新/髒檢查時boolean/修改狀態數組
onDelete刪除物件前void
preFlush / postFlushFlush 前/後void:批次處理
findDirty髒屬性檢測int[]:返回髒屬性索引,null 走預設
instantiate實例化實體Object:自定義構造,null 用預設
isTransient判斷瞬時態Boolean
getEntityName / getEntity元數據訪問String/Object
事務回調afterTransactionBegin、beforeTransactionCompletion、afterTransactionCompletionvoid

使用範例

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());

應用場景:審計日誌、自動時間戳、軟刪除標記、自定義髒檢查、實例化策略控制。

SchemaExport:映射文件正向生成 DDL

利用 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

資料庫實際建表結構與映射定義一致。

總結

  • Interceptor 提供細粒度生命週期切面,適合橫切關注點 (審計、安全、快取同步)。
  • SchemaExport 讓映射文件成為單一真實來源,支援開發期快速建表、測試環境自動佈署、版本控管 DDL 演進。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved