1. 核心配置檔
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//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>
<!-- 方言與顯示 SQL -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<!-- 註解實體類 -->
<mapping class="com.ij34.dao.New"/>
</session-factory>
</hibernate-configuration>
2. 實體類註解
package com.ij34.dao;
import javax.persistence.*;
@Entity
@Table(name = "test01")
public class New {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String title;
private String content;
// getter/setter 省略...
}
3. 測試類:建立 SessionFactory 並持久化
package com.ij34.web;
import org.hibernate.*;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.*;
import com.ij34.dao.New;
public class test01 {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration().configure();
ServiceRegistry sr = new StandardServiceRegistryBuilder()
.applySettings(conf.getProperties()).build();
SessionFactory sf = conf.buildSessionFactory(sr);
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
New n = new New();
n.setTitle("hello");
n.setContent("hello world");
session.save(n);
tx.commit();
session.close();
sf.close();
}
}
關鍵點提示
@Entity 標記實體,@Table 指定表名。
@Id + @GeneratedValue 定義主鍵生成策略(此處用自增)。
- Hibernate 4/5 建議使用
StandardServiceRegistryBuilder 建立註冊表,再構建 SessionFactory。
hbm2ddl.auto=create 啟動時自動建表(僅開發測試用)。