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

Hibernate 入門實戰:從配置到持久化類映射的完整流程

     編輯:Java 程式設計入門

Hibernate 核心定位

Let Java objects hibernate in the relational database.

  • Java 應用與關聯資料庫的橋樑
  • ORM 中間件:對象 ↔ 關係映射
  • 輕量級封裝 JDBC,提供面向對象資料訪問 API

專案結構

src/
├── entity/Customer.java           // 持久化類
├── hbm/Customer.hbm.xml           // O/R 映射文件
├── hibernate.cfg.xml              // Hibernate 配置
├── business/UseHibernate.java     // 業務邏輯
└── test/TestHibernate.java        // JUnit 測試

1. 持久化類規範

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 複製需求)
  • 無參構造器(反射實例化)
  • 標準 Getter/Setter(屬性存取)

2. 資料庫建表

CREATE DATABASE netstore;
CREATE TABLE customers (
    id BIGINT NOT NULL PRIMARY KEY,
    name VARCHAR(15),
    age INT
) ENGINE=MyISAM DEFAULT CHARSET=gb2312;

3. Hibernate 配置文件

<?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>

4. O/R 映射文件

<?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>

5. 業務邏輯:Session 生命週期與事務

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(); // 必須關閉,歸還連線
        }
    }
}

6. JUnit 測試驗證

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);
    }
}

7. 成功日誌特徵

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="..."/>
PropertyNotFoundExceptionGetter/Setter 命名不符 JavaBean檢查大小寫、前綴 get/set/is
連線失敗URL/驅動/帳密/資料庫未啟動逐項驗證,測試獨立 JDBC 連線
中文亂碼characterEncoding 未設或不匹配URL 加 useUnicode=true&characterEncoding=gb2312/utf8

現代化遷移提示

  • Hibernate 3/4/5/6 套件變更為 org.hibernate
  • 推薦使用 JPA 標準註解(@Entity、@Id、@Column)替代 .hbm.xml
  • SessionFactory 建構極其昂貴,必須單例、應用啟動時初始化
  • 生產環境必接連線池(HikariCP、Druid),關閉內建池

總結

Hibernate 入門核心路徑:持久化類 → 映射文件 → 配置文件 → SessionFactory → Session → Transaction → CRUD。掌握這條主線,理解物件狀態轉換(瞬時/持久/游離)、一級快取、延遲載入、事務邊界,即可駕馭 Hibernate 進行高效企業級資料持久化開發。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved