<dependencies>
<dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId><version>5.6.15.Final</version></dependency>
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version></dependency>
<dependency><groupId>org.slf4j</groupId><artifactId>slf4j-simple</artifactId><version>2.0.9</version></dependency>
</dependencies>
<?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/hibernate_first?useSSL=false&serverTimezone=UTC</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">ab12</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property> <!-- 自動建表/更新 -->
<mapping resource="com/hibernate/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
package com.hibernate;
import java.util.Date;
public class User {
private String id;
private String name;
private String password;
private Date createTime;
private Date expireTime;
// Getter/Setter 省略
}
<?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.hibernate.User" table="t_user">
<id name="id">
<generator class="uuid"/>
</id>
<property name="name"/>
<property name="password"/>
<property name="createTime"/>
<property name="expireTime"/>
</class>
</hibernate-mapping>
package com.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory SESSION_FACTORY = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try { return new Configuration().configure().buildSessionFactory(); }
catch (Throwable ex) { throw new ExceptionInInitializerError(ex); }
}
public static SessionFactory getSessionFactory() { return SESSION_FACTORY; }
public static void shutdown() { getSessionFactory().close(); }
}
package com.hibernate;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class ExportDB {
public static void main(String[] args) {
Configuration cfg = new Configuration().configure();
new SchemaExport(cfg).create(true, true); // 輸出 SQL 並執行
}
}
package com.hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.Date;
public class Client {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
// 新增
User user = new User();
user.setName("張三");
user.setPassword("123");
user.setCreateTime(new Date());
session.save(user); // 持久化
tx.commit();
System.out.println("保存成功,ID: " + user.getId());
// 查詢
User loaded = session.get(User.class, user.getId());
System.out.println("查詢: " + loaded.getName());
// 修改
tx = session.beginTransaction();
loaded.setPassword("456");
session.update(loaded);
tx.commit();
// 刪除
tx = session.beginTransaction();
session.delete(loaded);
tx.commit();
} catch (Exception e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
HibernateUtil.shutdown();
}
}
}
save() 使對象變為持久狀態,事務提交時自動同步到數據庫。get() 同一 ID 只發一條 SQL。create (每次重建)、update (更新)、validate (驗證)、none (禁用)。生產環境建議用 Flyway/Liquibase 管理遷移。Hibernate 以「配置映射、操作對象、自動生成 SQL」極大提升開發效率。掌握「配置 → 映射 → SessionFactory → Session → Transaction → CRUD」核心鏈路,理解對象三大狀態轉換與緩存機制,即可駕輕就熟處理企業級持久層開發。