本文總結Hibernate中常見(jiàn)的異常。
當出現net.sf.hibernate.MappingException: Error reading resource:…異常時(shí)一般是因為映射文件出現錯誤。
當出現net.sf.hibernate.MappingException: Resource: … not found是因為XML配置文件沒(méi)找到所致,有可能是放置目錄不正確,或者沒(méi)將其加入hibernate.cfg.xml中。
當出現net.sf.hibernate.PropertyNotFoundException: Could not find a setter for property name in class …時(shí),原因一般是因為XML映射文件中的屬性與對應的Java類(lèi)中的屬性的getter或setter方法不一致。
當出現org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save():異常時(shí),一般是因為<id>元素配置不正確,<id>元素缺少其子元素<generator></generator>的配置引起。
解決方案:<id>元素映射了相應數據庫表的主鍵字段,對其子元素<generator class="">,其中class的取值可以為increment、identity、sequence、hilo、native……等,更多的可參考hibernate參考文檔,一般取其值為native 。具體可參考2.2.2.1小節。
當出現a different object with the same identifier value was already associated with the session時(shí),一般是因為在hibernate中同一個(gè)session里面有了兩個(gè)相同標識但是是不同實(shí)體。
有如下幾種解決方案:
(1)使用session.clean(),如果在clean操作后面又進(jìn)行了saveOrUpdate(object)等改變數據狀態(tài)的操作,有可能會(huì )報出"Found two representations of same collection"異常。
(2)使用session.refresh(object),當object不是數據庫中已有數據的對象的時(shí)候,不能使用session.refresh(object)因為該方法是從hibernate的session中去重新取object,如果session中沒(méi)有這個(gè)對象,則會(huì )報錯所以當你使用saveOrUpdate(object)之前還需要判斷一下。
(3)session.merge(object),Hibernate里面自帶的方法,推薦使用。
當出現SQL Grammer Exception,Could not execute JDBC batch update異常時(shí),一般是由如下問(wèn)題引起:
(1)SQL語(yǔ)句中存在語(yǔ)法錯誤或是傳入的數據有誤;
(2)數據庫的配置不合法,或者說(shuō)是配置有誤。較容易出現的有數據表的映射文件(,hbm.xml文件)配置有誤;Hibernate.cfg.xml文件配置有誤;
(3) 當前的數據庫用戶(hù)權限不足,不能操作數據庫。以是以Oracle 數據庫為例,這種情況下在錯誤提示中會(huì )顯示java.sql.BatchUpdateException: ORA-01031: insufficient privileges這樣的信息。
針對上面的各種原因,開(kāi)發(fā)人員可以找出對應的解決方案。
聯(lián)系客服