在開發 Web 應用時,Hibernate 映射檔 (*.hbm.xml) 配置錯誤是常見問題。本文整理兩個典型異常案例,說明成因與修正方法,幫助開發者快速定位並解決問題。
org.springframework.orm.hibernate3.HibernateSystemException:
ids for this class must be manually assigned before calling save():
com.ebupt.ncsp.assist.service.department.domain.Department
nested exception is org.hibernate.id.IdentifierGenerationException:
ids for this class must be manually assigned before calling save(): ...
<id> 元素映射資料表主鍵,但缺少子元素 <generator> 配置。Hibernate 無法決定主鍵生成方式,導致儲存時拋出異常。
在 <id> 下添加 <generator class="native"/> (或 increment、identity、sequence、hilo 等,視資料庫支援度而定)。建議使用 native 讓 Hibernate 自動選擇適合底層資料庫的策略。
<id name="id" column="dept_id">
<generator class="native"/>
</id>
經驗提醒:手動編寫映射檔易疏漏細節,新手建議多參考官方文件,或使用自動生成工具 (如 Middlegen、Hibernate Tools) 降低錯誤率。
org.springframework.orm.hibernate3.HibernateSystemException:
exception setting property value with CGLIB
(set hibernate.cglib.use-reflection-optimizer=false for more info)
setter of com.info.beran.com.SetComCode
nested exception is org.hibernate.PropertyAccessException: ...
Integer。Integer、Long 等),包裝類型可接受 null,避免 PropertyAccessException。<property name="someNumber" type="java.lang.Integer" column="num_col"/>
結論:上述兩個異常若使用自動生成工具通常不會發生。手動配置時務必核對 <id> 生成器與屬性型別對應關係,養成查閱參考文件的習慣。