Hibernate 能從實體映射元數據自動生成 DDL,但「能跑」不代表「好用」。本文闡述自動生成 Schema 的侷限性、DBA 介入時機、映射元數據反饋機制,並示範如何匯出 DDL 檔案供審核優化,建立「開發自動化、DBA 治理、元數據同步」的良性循環。
| 自動支援 | 需人工補強 |
|---|---|
| 基本建表、主鍵、外鍵、非空約束 | Tablespace、分區、壓縮、加密等儲存屬性 |
| 依主鍵生成策略建立 Sequence/Identity | 進階索引(函數索引、部分索引、全文索引) |
| 基本型別映射 | 資料庫特有優化 Hint、平行查詢設定 |
鐵律:未經 DBA 審核的自動生成 Schema 絕不可部署上線。
.sql 檔.hbm.xml / JPA 註解(@Table(indexes=...)、@Index 等)Hibernate 內建 SchemaExport 工具,可直接輸出文字檔:
java -cp hibernate-core.jar:... org.hibernate.tool.hbm2ddl.SchemaExport \
--config=hibernate.cfg.xml \
--output=schema.sql \
--format \
--delimiter=;
或在程式碼中呼叫:
Configuration cfg = new Configuration().configure();
SchemaExport export = new SchemaExport(cfg);
export.setOutputFile("schema.sql");
export.setFormat(true);
export.create(true, false); // 只輸出檔案,不執行
@Index(name="idx_user_email", columnList="email")、複合索引順序匹配查詢模式@UniqueConstraint、@Check(資料庫端驗證)@Table(..., options="ENGINE=InnoDB ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=8")UserType 映射 JSON、幣值、經緯度等複雜型別生產環境嚴禁使用 hbm2ddl.auto=update/create-drop。採用:
V{x.y.z}__description.sqlHibernate Schema 生成是「起草工具」,非「定稿工具」。建立 DDL 匯出 → DBA 審核 → 元數據回寫 → 版本化遷移 的標準化流程,才能兼顧開發效率與資料庫穩定性。