學 Hibernate 的第一步,就是把「HelloWorld」跑起來。這個範例會建立一個 Customer 類別、對應一張 customer 表,然後用 Hibernate 把物件存進 PostgreSQL。跑通它,你就掌握了 Hibernate 九成的基礎流程。
webApp/ ├── classes/ │ └── hibernate.cfg.xml ├── web.xml ├── Customer.hbm.xml ├── java files └── lib/ # 存放 hibernate 與資料庫驅動所需的 jar
<?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="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/customers</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">yang</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping resource="Customer.hbm.xml" />
</session-factory>
</hibernate-configuration>
幾個關鍵設定:dialect 決定 SQL 方言;show_sql 與 format_sql 讓你能在 console 看到實際送出的 SQL,初學階段務必打開;current_session_context_class=thread 讓 Session 與當前執行緒綁定。
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"https://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>My Web Application</display-name>
</web-app>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"https://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="yang.www.Customer" table="customer">
<id name="id" column="ID" type="long" length="10">
<generator class="increment" />
</id>
<property name="name" column="NAME" type="string" length="20"
not-null="true" />
<property name="year" column="YEAR" type="int" not-null="true" />
</class>
</hibernate-mapping>
<generator class="increment"> 表示主鍵由 Hibernate 在記憶體中遞增產生,適用於小型應用;正式環境多改用 sequence 或 identity。
package yang.www;
import java.io.Serializable;
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
private long id;
private String name;
private int year;
public long getId() { return id; }
public String getName() { return name; }
public int getYear() { return year; }
public void setId(long id) { this.id = id; }
public void setName(String name) { this.name = name; }
public void setYear(int year) { this.year = year; }
}
實作 Serializable 是好習慣,Hibernate 在跨 Session 傳遞物件或做快取時會用到。
package yang.www;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
public class HibernateMain {
public static void main(String[] args) {
Configuration config = new Configuration();
config.configure(); // 檔名不是 hibernate.cfg.xml 時,把檔名傳入
SessionFactory sessionFactory = config.buildSessionFactory(); // 相當於 JDBC 註冊驅動
Session session = sessionFactory.openSession(); // 相當於 JDBC getConnection
Transaction tx = session.beginTransaction(); // Hibernate 操作必須啟動事務
Customer user = new Customer(); // 建立持久化物件
user.setName("YangZhiYong");
user.setYear(22);
session.save(user); // 暫存
tx.commit(); // 真正寫入資料庫
session.close();
sessionFactory.close();
}
}
把 SessionFactory 與 JDBC 的 analogy 記住就夠了:Configuration 讀設定 → SessionFactory 建立連線池工廠(重物件,全應用共用一個)→ Session 是工作單元(輕物件,用完關掉)→ Transaction 包住寫入。
執行這個測試類別,若 console 印出類似以下的內容,代表你成功了:
Hibernate: insert into customer (NAME, YEAR, ID) values (?, ?, ?)
看到這行 SQL,就表示 Hibernate 已經把 Java 物件翻譯成資料庫操作並成功提交。如果出現例外,請依序檢查三件事:jar 是否齊全、cfg 檔是否在 classes 根目錄、hbm 檔是否被 <mapping resource> 正確指向。九成的入門錯誤都在這三處。
跑通之後,下一步可以試著用 session.get(Customer.class, 1L) 讀回來,再用 session.createQuery("from Customer") 查全部,你會發現 ORM 的日常操作其實非常直觀。