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

Hibernate 3.1 vs 3.2:identity 主鍵生成策略差異導致 MappingException 解決記

     編輯:Java 相關知識

專案從 Hibernate 3.1 升級至 3.2 後,原本正常的 <generator class="identity"/> 主鍵生成策略拋出 MappingException: Dialect does not support identity key generation。本文記錄排查過程、根本原因與解決方案。

錯誤堆疊

Exception in thread "main" net.sf.hibernate.MappingException:
Dialect does not support identity key generation
    at net.sf.hibernate.dialect.Dialect.getIdentitySelectString(Dialect.java:305)
    at net.sf.hibernate.persister.AbstractEntityPersister.<init>(AbstractEntityPersister.java:646)
    at net.sf.hibernate.persister.EntityPersister.<init>(EntityPersister.java:690)
    at net.sf.hibernate.persister.PersisterFactory.createClassPersister...

原配置 (Hibernate 3.1 正常)

<id name="kid" type="java.lang.Long">
  <column name="KID" precision="22" scale="0"/>
  <generator class="identity"/>
</id>

解決方案:改用 increment

<id name="kid" type="java.lang.Long">
  <column name="KID" precision="22" scale="0"/>
  <generator class="increment"/>
</id>

修改後程式正常運行。

主鍵生成策略對照表

策略適用資料庫說明
increment所有 (單進程)Hibernate 內存計數器,最大值+1,**不適用叢集/多進程**
identityMySQL、SQL Server、Sybase、DB2、PostgreSQL資料庫自增欄位 (AUTO_INCREMENT/IDENTITY)
sequenceOracle、DB2、PostgreSQL資料庫 Sequence 物件
hilo支援 Sequence 的資料庫高低位算法,減少資料庫往返
native跨資料庫移植自動選擇 identity/sequence/hilo
uuid所有UUID 字串,無序、唯一
assigned所有應用程式手動指定

根本原因分析

  • Hibernate 3.1:對不支援 identity 的方言 (如 Oracle) 可能僅警告或靜默 fallback
  • Hibernate 3.2:嚴格檢查方言支援度,Dialect.getIdentitySelectString() 若回傳 null 則直接拋 MappingException
  • 本案例資料庫:推測為 Oracle 或其他不支援 identity 的資料庫,但映射檔誤用 identity

正確選擇建議

  1. MySQL / SQL Server:identity (或 native)
  2. Oracle 12c+:identity (支援 IDENTITY 欄位) 或 sequence
  3. Oracle 11g 及以下:sequence (需建立 Sequence 物件)
  4. 跨資料庫移植專案:native (自動適配)
  5. 單機應用、無併發:increment (效能最好,但**嚴禁叢集**)

遷移檢查清單

  • [ ] 確認目標資料庫支援的主鍵生成方式
  • [ ] 檢查所有 .hbm.xml 中的 <generator> 設定
  • [ ] 方言配置正確:hibernate.dialect=org.hibernate.dialect.Oracle10gDialect 等
  • [ ] 測試實體持久化、批次插入效能
  • [ ] 叢集環境**禁止使用 increment**

教訓總結

  1. 升級框架版本時,**必須閱讀遷移指南與 Breaking Changes**
  2. 主鍵生成策略**強綁定資料庫特性**,不可想當然複製配置
  3. increment 看似通用但**極度危險** (叢集下主鍵衝突),僅限單機開發測試
  4. 優先使用 native 或明確指定資料庫支援的策略
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved