Let Java objects hibernate in the relational database.
src/ ├── entity/Customer.java // 持久化類 ├── hbm/Customer.hbm.xml // O/R 映射文件 ├── hibernate.cfg.xml // Hibernate 配置 ├── business/UseHibernate.java // 業務邏輯 └── test/TestHibernate.java // JUnit 測試
package entity;
import java.io.Serializable;
public class Customer implements Serializable {
private Integer id;
private String name;
private int age;
// 無參構造器(Hibernate 必須)
public Customer() {}
// 標準 Getter/Setter(JavaBean 規範)
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
關鍵要求:
Serializable(分布式/Session 複製需求)CREATE DATABASE netstore;
CREATE TABLE customers (
id BIGINT NOT NULL PRIMARY KEY,
name VARCHAR(15),
age INT
) ENGINE=MyISAM DEFAULT CHARSET=gb2312;
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 2.0//EN"
"https://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.use_outer_join">false</property>
<property name="hibernate.dialect">net.sf.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/netstore</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.connection.useUnicode">true</property>
<property name="hibernate.connection.characterEncoding">gb2312</property>
<mapping resource="hbm/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"https://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="entity.Customer" table="customers">
<id name="id" type="java.lang.Integer" column="id">
<generator class="assigned"/> <!-- 手動指定 ID -->
</id>
<property name="name" type="java.lang.String" column="name" length="15"/>
<property name="age" type="int" column="age" length="11"/>
</class>
</hibernate-mapping>
package business;
import entity.Customer;
import net.sf.hibernate.*;
public class UseHibernate {
private static SessionFactory sessionFactory;
static {
Configuration cfg = new Configuration().configure();
sessionFactory = cfg.buildSessionFactory(); // 昂貴操作,僅初始化一次
}
public void saveCustomer(Customer customer) throws Exception {
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(customer);
tx.commit();
} catch (Exception e) {
if (tx != null) tx.rollback();
throw e;
} finally {
session.close(); // 必須關閉,歸還連線
}
}
}
package test;
import business.UseHibernate;
import entity.Customer;
import junit.framework.TestCase;
public class TestHibernate extends TestCase {
public void testSave() {
Customer c = new Customer();
c.setId(330121);
c.setName("huhpreal");
c.setAge(24);
UseHibernate uh = new UseHibernate();
uh.saveCustomer(c);
}
}
Hibernate 2.0.3 hibernate.properties not found using CGLIB reflection optimizer JVM proxy support: true Configuration resource: /hibernate.cfg.xml Mapping resource: hbm/Customer.hbm.xml Mapping class: entity.Customer -> customers Building session factory Using dialect: net.sf.hibernate.dialect.MySQLDialect Hibernate connection pool size: 20 echoing all SQL to stdout Hibernate 配置使用成功
| 現象 | 原因 | 解決 |
|---|---|---|
| MappingException: Unknown entity | 映射文件未在 cfg.xml 註冊 | 添加 <mapping resource="..."/> |
| PropertyNotFoundException | Getter/Setter 命名不符 JavaBean | 檢查大小寫、前綴 get/set/is |
| 連線失敗 | URL/驅動/帳密/資料庫未啟動 | 逐項驗證,測試獨立 JDBC 連線 |
| 中文亂碼 | characterEncoding 未設或不匹配 | URL 加 useUnicode=true&characterEncoding=gb2312/utf8 |
org.hibernate@Entity、@Id、@Column)替代 .hbm.xmlSessionFactory 建構極其昂貴,必須單例、應用啟動時初始化Hibernate 入門核心路徑:持久化類 → 映射文件 → 配置文件 → SessionFactory → Session → Transaction → CRUD。掌握這條主線,理解物件狀態轉換(瞬時/持久/游離)、一級快取、延遲載入、事務邊界,即可駕馭 Hibernate 進行高效企業級資料持久化開發。