Hibernate 可根據實體註解自動建立、更新或驗證資料庫結構。本文介紹三種啟動建表方式:手動 DDL、組態屬性 hbm2ddl.auto、程式化 SchemaExport。
@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 略
}
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;
<property name="hbm2ddl.auto">create</property>
hbm2ddl.auto 可選值:
| 值 | 行為 |
|---|---|
create | 啟動時 Drop 再 Create (資料全失) |
create-drop | 啟動 Create,關閉 SessionFactory 時 Drop |
update | 啟動時嘗試更新結構 (不刪除資料,僅新增欄位/表) |
validate | 啟動時驗證結構一致性,不修改資料庫 |
none | 不做任何事 (預設) |
Configuration cfg = new AnnotationConfiguration().configure();
SchemaExport export = new SchemaExport(cfg);
// create(script, export)
// script: 是否輸出 DDL 至 console
// export: 是否真正執行至資料庫
export.create(true, true);
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 審核執行手動遷移腳本。<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>