利用 hibernate.cfg.xml 與 *.hbm.xml 映射檔,程式化建立資料庫表結構,免寫 SQL DDL。
<?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)。
<?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>
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("資料表建立完成。");
}
}
| 值 | 行為 |
|---|---|
| create | 啟動時建立,關閉時刪除 (僅開發用) |
| create-drop | SessionFactory 關閉時刪除 |
| update | 啟動時更新結構 (不刪除資料),生產慎用 |
| validate | 啟動時驗證結構一致性,不修改 |
| none | 不自動處理 (生產預設) |