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

Hibernate SchemaExport:從映射檔自動建立資料庫結構

     編輯:J2EE

Hibernate 自動生成 DDL (SchemaExport)

利用 hibernate.cfg.xml 與 *.hbm.xml 映射檔,程式化建立資料庫表結構,免寫 SQL DDL。

1. hibernate.cfg.xml 關鍵設定


<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "https://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibtest?useSSL=false</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">123456</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">create</property> <!-- 自動建表 --> 
    <mapping resource="com/hibtest/User.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

注意:驅動類、方言、連線字串需依資料庫版本調整 (MySQL 8 用 com.mysql.cj.jdbc.Driver、MySQL8Dialect、useSSL=false、serverTimezone=UTC)。

2. 映射檔 User.hbm.xml


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "https://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="com.hibtest.User" table="user">
    <id name="id" column="id">
      <generator class="identity"/>
    </id>
    <property name="username" column="username" length="32" not-null="true"/>
    <property name="password" column="password" length="64"/>
    <property name="email" column="email" length="100"/>
    <property name="createdAt" column="created_at" type="timestamp"/>
  </class>
</hibernate-mapping>

3. 程式化執行 SchemaExport


import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import java.io.File;

public class InitDatabase {
    public static void main(String[] args) {
        Configuration cfg = new Configuration().configure(new File("hibernate.cfg.xml"));
        System.out.println("建立資料表中...");
        SchemaExport export = new SchemaExport(cfg);
        export.create(true, true); // 輸出 SQL 到標準輸出、執行建表
        System.out.println("資料表建立完成。");
    }
}

進階:hbm2ddl.auto 選項

最佳實務

  • 開發環境用 create 或 update;生產環境禁用自動 DDL,改用 Flyway/Liquibase 管理遷移腳本。
  • 映射檔建議改用 JPA 註解 (@Entity, @Table, @Column) 簡化維護。
  • 命名策略:PhysicalNamingStrategyStandardImpl 控制表/欄位命名規則 (駝峰轉底線等)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
值行為
create啟動時建立,關閉時刪除 (僅開發用)
create-dropSessionFactory 關閉時刪除
update啟動時更新結構 (不刪除資料),生產慎用
validate啟動時驗證結構一致性,不修改
none不自動處理 (生產預設)