| 概念 | 說明 |
|---|---|
| 持久化框架 | 將內存對象永久保存到數據庫(狹義);廣義上包含 CRUD 等所有數據庫操作 |
| ORM (Object-Relational Mapping) | 對象關系映射:類↔表、對象↔行、屬性↔列。通過映射文件描述對應關系 |
| hibernate.cfg.xml | 全局配置文件:數據庫連接、方言、映射文件引用、緩存策略等 |
| Entity.hbm.xml | 對象關系映射文件:定義實體類與表的字段映射、主鍵策略、關聯關系 |
| Session | 核心接口:單線程、短生命周期、一級緩存持有者,相當於 JDBC Connection |
| SessionFactory | 重量級工廠:線程安全、應用啟動構建一次,根據配置生成 Session |
| Transaction | 事務接口:通過 Session.openTransaction() 獲取,支持 ACID |
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"https://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 數據庫連接 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<!-- Hibernate 核心屬性 -->
<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- 映射文件 -->
<mapping resource="com/nucsoft/hibernate/News.hbm.xml"/>
</session-factory>
</hibernate-configuration>
package com.nucsoft.hibernate;
import java.util.Date;
public class News {
private int id;
private String title, author;
private Date date;
// Getter/Setter、equals/hashCode 省略
}
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.nucsoft.hibernate.News" table="news" schema="hibernate">
<id name="id">
<column name="id" sql-type="int(11)"/>
</id>
<property name="title">
<column name="title" sql-type="varchar(255)" not-null="true"/>
</property>
<property name="author">
<column name="author" sql-type="varchar(50)" length="50" not-null="true"/>
</property>
<property name="date">
<column name="date" sql-type="date" not-null="true"/>
</property>
</class>
</hibernate-mapping>
@Test
public void testSave() {
// 1. 構建 SessionFactory
Configuration cfg = new Configuration().configure(); // 默認讀取 classpath:hibernate.cfg.xml
ServiceRegistry sr = new ServiceRegistryBuilder()
.applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory sf = cfg.buildSessionFactory(sr);
// 2. 開啟 Session
Session session = sf.openSession();
// 3. 開啟事務
Transaction tx = session.beginTransaction();
// 4. 執行持久化操作
News news = new News();
news.setTitle("Title");
news.setAuthor("tom");
news.setDate(new Date(System.currentTimeMillis()));
session.save(news);
// 5. 提交事務
tx.commit();
// 6. 關閉資源
session.close();
sf.close();
}
Configuration.configure() 默認加載 classpath 下的 hibernate.cfg.xmlServiceRegistry 管理服務,構建 SessionFactory 需傳入beginTransaction() → 操作 → commit()/rollback()從 HelloWorld 入門,後續深入學習建議按以下模塊推進: