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

Hibernate 註解建立資料表完整流程 (SchemaExport、hbm2ddl.auto)

     編輯:J2EE

前言

Hibernate 可根據實體註解自動建立、更新或驗證資料庫結構。本文介紹三種啟動建表方式:手動 DDL、組態屬性 hbm2ddl.auto、程式化 SchemaExport。

1. 實體類別定義

@Entity
@Table(name = "E_USER", uniqueConstraints = @UniqueConstraint(columnNames = "yahoo"))
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    private String yahoo; // 暱稱,唯一
    // getter/setter 略
}

2. 三種建表方式

方式一:手動執行 DDL (生產環境建議)

DROP TABLE IF EXISTS `e_user`;
CREATE TABLE `e_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `yahoo` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `yahoo` (`yahoo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

方式二:hibernate.cfg.xml 設定 hbm2ddl.auto

<property name="hbm2ddl.auto">create</property>

hbm2ddl.auto 可選值:

值行為
create啟動時 Drop 再 Create (資料全失)
create-drop啟動 Create,關閉 SessionFactory 時 Drop
update啟動時嘗試更新結構 (不刪除資料,僅新增欄位/表)
validate啟動時驗證結構一致性,不修改資料庫
none不做任何事 (預設)

方式三:程式化 SchemaExport (整合測試/工具常用)

Configuration cfg = new AnnotationConfiguration().configure();
SchemaExport export = new SchemaExport(cfg);
// create(script, export)
// script: 是否輸出 DDL 至 console
// export: 是否真正執行至資料庫
export.create(true, true);

Hibernate 自動生成 DDL (MySQL 範例)

drop table if exists E_USER
create table E_USER (
    id integer not null auto_increment,
    yahoo varchar(255),
    primary key (id),
    unique (yahoo)
)

開發/測試/生產環境建議

  • 開發/單元測試:create-drop 或 SchemaExport.create(true,true),確保乾淨環境。
  • 整合測試/預演環境:update 或 Flyway/Liquibase 遷移腳本。
  • 生產環境:嚴禁 使用 hbm2ddl.auto,務必由 DBA 審核執行手動遷移腳本。

啟用 SQL 顯示 (除錯用)

<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved