新手自學 Hibernate 時,儲存實體拋出異常,常見錯誤訊息:
ids for this class must be manually assigned before calling save()could not generate identifierIdentifierGenerationException

| 策略 | 適用資料庫 | 註解/配置 | 說明 |
|---|---|---|---|
identity | MySQL, SQL Server, PostgreSQL (SERIAL) | @GeneratedValue(strategy = GenerationType.IDENTITY) | 資料庫自增,插入後回寫 ID |
sequence | Oracle, PostgreSQL, DB2 | @SequenceGenerator(name="seq", sequenceName="MY_SEQ") | 資料庫序列 |
table | 所有支援表的資料庫 | @TableGenerator(name="tab", table="ID_GEN") | 模擬序列表,效能較差 |
auto | 自動選擇 | @GeneratedValue(strategy = GenerationType.AUTO) | Hibernate 決定,可能不符預期 |
assigned | 手動指定 | 無 @GeneratedValue | 業務主鍵 (如 UUID、身分證號) |
-- MySQL
CREATE TABLE user (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50)
);
-- Oracle
CREATE SEQUENCE user_seq;
CREATE TABLE user (
id NUMBER PRIMARY KEY,
name VARCHAR2(50)
);
// MySQL 自增
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// ...
}
// Oracle 序列
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
@SequenceGenerator(name = "user_seq", sequenceName = "USER_SEQ", allocationSize = 1)
private Long id;
// ...
}
<property name="hibernate.id.new_generator_mappings">true</property>
<!-- true: 使用新生成器 (JPA 標準), false: 舊版相容 -->
allocationSize 是否與序列 INCREMENT BY 一致 (預設 50,序列常為 1)@Id 欄位上正確標註 @GeneratedValueSerializable 並覆寫 equals/hashCode// 開啟 SQL 顯示
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
// 觀察實際執行的 INSERT 語句是否包含 ID 欄位