天天看點

Hibernate開發中常見錯誤總結

org.hibernate.mappingexception: unknown entity: cn.itcast.hibernate717.helloworld.person

hibernate架構根本不知道person這個持久化類的存在

caused by: java.sql.sqlexception: field 'id' doesn't have a default value

如果主鍵的生成政策采取的是identity,而資料庫中表的主鍵不是自動生成機制,則報這樣的錯誤

org.hibernate.nonuniqueobjectexception: a different object with the same identifier value was already associated with the session: [cn.itcast.hibernate717.helloworld.person#1]

如果在hibernate中,有兩個對象,但是其id值是相同的,這樣的情況在hibernate中是不允許出現  (在hibernate中,強調對象的唯一性)

caused by: java.sql.batchupdateexception: cannot delete or update a parent row: a foreign key constraint fails (`test/orders`, constraint `fkc3df62e58940cce2` foreign key (`customer_id`) references `customer` (`id`))

違反了主外鍵限制的原則

org.hibernate.lazyinitializationexception: could not initialize proxy - no session

org.hibernate.transientobjectexception: object references an unsaved transient instance - save the transient instance before flushing: cn.itcast.hibernate717.manytomany.student

錯誤産生的原因:

在多對多時,代碼中寫了兩個對象。程式的意圖是通過級聯的方式把這兩個對象全部儲存到資料庫相應的表中。但是級聯在映射檔案中不存在,這個時候hibernate隻會認session.save中的參數代表的對象

而另外一個對象則認為是瞬态的對象,是以會報如此的錯誤

在使用hibernate時,報了 could not parse configuration: /hibernate.cfg.xml

這很有可能是hibernate.cfg.xml檔案出錯

此時可以先用浏覽器打開 hibernate.cfg.xml檔案 看看能不能正常顯示,如果不能,則說明配置檔案編寫有問題(比如dtd的url錯誤,标簽錯誤等),改正相應的錯誤後就不報異常了

1、錯誤一:在項目中要有commons-logging.jar,不然會報以下錯誤。

java.lang.noclassdeffounderror: org/apache/commons/logging/logfactory

2、錯誤二、

如果你添加了ehcache-1.5.0.jar,但是沒有加ehcache.xml,這時候将報錯。

slf4j-api-1.5.10.jar日志包,ehcache依賴

slf4j-jdk14-1.5.10.jar日志包,ehcache依賴

java.lang.noclassdeffounderror: edu/emory/mathcs/backport/java/util/concurrent/blockingqueue

在junit.test裡提示錯誤:nested exception is java.lang.noclassdeffounderror:

edu/emory/mathcs/backport/java/util/concurrent/blockingqueue

原因:沒有包含:backport-util-concurrent.jar

在spring/lib/concurrent/加上即可。

3、開始建立項目的時候都要把各種字元集統一

項目名右擊--->properties--->text file encoding(控制文本檔案内部的字元集,最好開始也要定義好)。

window-->preferences-->general-->content type的内容也要首先确定好。

4錯誤:

caused by: org.hibernate.hibernateexception: unable to instantiate default tuplizer [org.hibernate.tuple.entity.pojoentitytuplizer]

caused by: java.lang.reflect.invocationtargetexception

caused by: org.hibernate.propertynotfoundexception: could not find a getter for data in class cn.edu.hactcm.test.hibernate.event

這種錯誤是把配置檔案中的名字寫錯了的緣故。

5、易錯點:

在給date配置屬性的時候,需要制定資料類型,并且列名要改一下,應為date為資料庫的關鍵字。

錯誤6

org.hibernate.hibernateexception: no currentsessioncontext configured!

 at org.hibernate.impl.sessionfactoryimpl.getcurrentsession(sessionfactoryimpl.java:683)

sessionfactory 對象的建立代價很昂貴,它是線程安全的對象,它為所有的應用程式線程所共享。它隻建立一次,通常是在應用程式啟動的時候,由一個 configuraion 的執行個體來建立。

session 對象的建立代價比較小,是非線程安全的,對于單個請求,單個會話、單個的 工作單元而言,它隻被使用一次,然後就丢棄。隻有在需要的時候,一個 session 對象 才會擷取一個 jdbc 的 connection(或一個datasource)對象,是以假若不使用的時候它不消費任何資源。

此外我們還要考慮資料庫事務。資料庫事務應該盡可能的短,降低資料庫中的鎖争用。資料庫長事務會阻止你的應用程式擴充到高的并發負載。是以,假若在使用者思考期間讓資料庫事務開着,直到整個工作單元完成才關閉這個事務,這絕不是一個好的設計。

一個操作單元(unit of work)的範圍是多大?單個的 hibernate session 能跨越多個資料庫事務嗎?還是一個 session 的作用範圍對應一個資料庫事務的範圍?應該何時打開 session,何時關閉 session,你又如何劃分資料庫事務的邊界呢?我們将在後續章節解決這些問題。

錯誤7

 at cn.edu.hactcm.test.hibernate.eventmanager.createandstoreevent(eventmanager.java:12)

 at sun.reflect.nativemethodaccessorimpl.invoke0(native method)

錯誤原因:在hibernate.cfg.xml中沒有配置正确,如果是web應用增加配置

<property name="current_session_context_class">jta</property>

如果是java應用,增加如下配置

<property name="current_session_context_class">thread</property>

不能自動建立表

需要加上<property name="hbm2ddl.auto">update</property>

錯誤7,事務送出(commit)之後session就已經關閉了,不用再寫session.close()了。

錯誤8,

嚴重: error configuring application listener of class org.springframework.web.context.contextloaderlistener

java.lang.classnotfoundexception: org.springframework.web.context.contextloaderlistener

清空部署的項目重新啟動。

錯誤9

14:57:53,624 error contextloader:215 - context initialization failed

org.springframework.beans.factory.beancreationexception: error creating bean with name 'sessionfactory' defined in file [d:\software\apache-tomcat-6.0.14\webapps\hactcmoa\web-inf\classes\applicationcontext.xml]: invocation of init method failed; nested exception is java.lang.noclassdeffounderror: javax/persistence/entitylisteners

 at org.springframework.beans.factory.support.abstractautowirecapablebeanfactory.initializebean(abstractautowirecapablebeanfactory.java:1337)

caused by: java.lang.noclassdeffounderror: javax/persistence/entitylisteners

 at org.hibernate.cfg.annotations.reflection.jpametadataprovider.getdefaults(jpametadataprovider.java:96)

hibernate3.6依賴hibernate-jpa-2.0-api-1.0.0.final.jar。應該把這個導進去。然後再remove deployment(移除部署好的向項目重新部署即可。)

錯誤10

 exception sending context initialized event to listener instance of class org.springframework.web.context.contextloaderlistener

說明配置web.xml中的

<listener>

 <listener-class>org.springframework.web.context.contextloaderlistener</listener-class>

</listener>

需要日志包

錯誤11

19:09:59,958 error contextloader:215 - context initialization failed

org.springframework.beans.factory.beancreationexception: error creating bean with name 'genericserviceimpl' defined in file [d:\software\apache-tomcat-6.0.14\webapps\hactcmoa\web-inf\classes\cn\edu\hactcm\bean\genericserviceimpl.class]: instantiation of bean failed; nested exception is org.springframework.beans.beaninstantiationexception: could not instantiate bean class [cn.edu.hactcm.bean.genericserviceimpl]: constructor threw exception; nested exception is java.lang.classcastexception: sun.reflect.generics.reflectiveobjects.typevariableimpl cannot be cast to java.lang.class

 at org.springframework.beans.factory.support.abstractautowirecapablebeanfactory.instantiatebean(abstractautowirecapablebeanfactory.java:883)

 at org.springframework.beans.factory.support.abstractautowirecapablebeanfactory.createbeaninstance(abstractautowirecapablebeanfactory.java:839)

caused by: org.springframework.beans.beaninstantiationexception: could not instantiate bean class [cn.edu.hactcm.bean.genericserviceimpl]: constructor threw exception; nested exception is java.lang.classcastexception: sun.reflect.generics.reflectiveobjects.typevariableimpl cannot be cast to java.lang.class

 at org.springframework.beans.beanutils.instantiateclass(beanutils.java:115)

caused by: java.lang.classcastexception: sun.reflect.generics.reflectiveobjects.typevariableimpl cannot be cast to java.lang.class

 at cn.edu.hactcm.bean.genericdaoimpl.<init>(genericdaoimpl.java:33)

2012-11-20 19:09:59 org.apache.catalina.core.standardcontext listenerstart

嚴重: exception sending context initialized event to listener instance of class org.springframework.web.context.contextloaderlistener

 at org.springframework.beans.factory.support.simpleinstantiationstrategy.instantiate(simpleinstantiationstrategy.java:61)

 at org.springframework.beans.factory.support.abstractautowirecapablebeanfactory.instantiatebean(abstractautowirecapablebeanfactory.java:877)

 ... 40 more

這種錯誤的原因是:在寫事務的時候 

@transactional

@suppresswarnings("unchecked")

public class genericdaoimpl<t> implements genericdao<t> {

而寫下面的時候寫成如下的了。

@service

public class genericserviceimpl<t> extends genericdaoimpl<t> implements genericservice<t> {

應該寫成:

錯誤12

org.apache.jasper.jasperexception: /left.jsp(73,8) attribute cssclass invalid for tag action according to tld

原因:在<s:actioin>标簽中不能寫cssclass屬性

錯誤13:

<s:form action="universityaction_collegeadd.action">

應該寫成:<s:form action="/universityaction_collegeadd.action">要加上“/”.s

錯誤14:

org.hibernate.hibernateexception:*** is not valid without active transaction

這種錯誤是因為使用的是getcurrentsession導緻的,解決這種問題的辦法是将getcurrentsession

改成opensession()這樣就可以解決着種問題了。

這種錯誤适應為在hibernate.hbm.xml中配置了如下參數:

将這一句删除後就沒有問題了。

錯誤15:

因為struts.xml中<action/>的中class的名稱不是action的名稱導緻錯誤

錯誤16

org.springframework.beans.factory.beancreationexception: error creating bean with name 'chapterdaoimpl':

injection of resource fields failed; nested exception is org.springframework.beans.factory.beancreationexception: error creating bean with name 'sessionfactory' defined in file

[d:\software\apache-tomcat-6.0.14\webapps\hactcmoa\web-inf\classes\applicationcontext.xml]:

invocation of init method failed; nested exception is org.hibernate.mappingexception:

repeated column in mapping for entity: cn.edu.hactcm.domain.major column:

secondaryacademy_id (should be mapped with insert="false" update="false")

原因:

<set name="users">

 <key column="secondaryacademy_id" not-null="true"/>

 <one-to-many class="user"/>

</set>

去掉:not-null="true"

錯誤17

org.hibernate.hibernateexception: illegal attempt to associate a collection with two open sessions

原因代碼寫成了:

//院校隻能有一個,從資料庫中找出這個大學對象,然後将它存進去。

  university university = universityservice.get(2l);

  model.setuniversity(university);

  secondaryacademyservice.save(model);

  universityservice.delete(1l);

當get了的時候開啟了一個session,delete了的時候又開啟了一個session.

錯誤18:

如果在many-to-one端加上了 not-null="true"。并且這着時候在<one-to-many>對應的set結合中加了inverse="true"

如果沒有對應的外鍵,這時候将報如下錯誤:

org.hibernate.propertyvalueexception: not-null property references a null or transient value: cn.edu.hactcm.domain.secondaryacademy.university

    org.hibernate.engine.nullability.checknullability(nullability.java:100)

錯誤19:

org.apache.jasper.jasperexception: org.apache.jasper.jasperexception: unable to load class for jsp

如果把如下标簽寫成如下的了,會出現以上錯誤。

<s:a action="${pagecontext.request.contextpath}/secondaryacademyaction_deletesecondaryacademy?id=%{id}">删除</s:a>

改錯辦法是:

去掉:${pagecontext.request.contextpath}/

錯誤20:

21:00:52,568 debug connectionmanager:464 - releasing jdbc connection [ (open preparedstatements: 0, globally: 0) (open resultsets: 0, globally: 0)]

21:00:52,568 debug connectionmanager:325 - transaction completed on session with on_close connection release mode; be sure to close the session to release jdbc resources!

exception in thread "main" org.springframework.transaction.transactionsystemexception: could not commit hibernate transaction; nested exception is org.hibernate.transactionexception: transaction not successfully started

 at org.springframework.orm.hibernate3.hibernatetransactionmanager.docommit(hibernatetransactionmanager.java:659)

 at org.springframework.transaction.support.abstractplatformtransactionmanager.processcommit(abstractplatformtransactionmanager.java:709)

caused by: org.hibernate.transactionexception: transaction not successfully started

 at org.hibernate.transaction.jdbctransaction.commit(jdbctransaction.java:127)

錯誤原因是:

  session session = sessionfactory.getcurrentsession();

  transaction tx = session.begintransaction();

  // 擷取題型資訊

  list<type> types = xmlutils.gettypes();

  iterator<type> iterator = types.iterator();

  while (iterator.hasnext()) {

   type type = iterator.next();

   session.save(type);

  }

  session.flush();

  session.clear();

  tx.commit();

  session.close();

這裡的session session = sessionfactory.getcurrentsession();不能和session.flush();session.clear();tx.commit();session.close();同時使用

錯誤21:caused by: com.mchange.v2.resourcepool.resourcepoolexception: attempted to use a closed or broken resource pool

解決方案1:重新開機mysql。

解決這個異常需要修改設定成如下:

<property name="acquireretryattempts">

    <value>30</value>

</property>

<property name="acquireretrydelay">

    <value>100</value>

<property name="breakafteracquirefailure">

    <value>false</value>

- acquireretryattempts

default: 30

defines how many times c3p0 will try to acquire a new connection from the database before giving up. if this value is less than or equal to zero, c3p0 will keep trying to fetch a connection indefinitely

- acquireretrydelay

default: 1000

milliseconds, time c3p0 will wait between acquire attempts.

- breakafteracquirefailure

default: false

if true, a pooled datasource will declare itself broken and be permanently closeed if a connection cannot be obtained from the database after making acquireretryattempts to acquire one. if false, failure to obtain a connection will cause all threads waiting for the pool to acquire a connection to throw an exception, but the datasource will remain valid, and will attempt to acquire again following a call to getconnection().

錯誤22

java.lang.indexoutofboundsexception: index: 0, size: 0

因為在通過登陸名和密碼方式查詢使用者時寫成了:

return (user)getsession().createquery(

    "from " + clazz.getsimplename() //查詢哪個表

    + " u where u.loginname = ? and u.password = ?")//查詢條件

    .setparameter(0, loginname)  //登入名

    .setparameter(1, password)//注意這裡的password要經過三次md5加密。

    .list()

    .get(0); 

而這裡包括空值得情況。要對list集合先進行判斷,如果list集合有元素,才能通過.get(0)方式去,如果為空,那麼用get(0)的時候就會出錯。

錯誤23:

stacktraces

java.lang.numberformatexception: null

    java.lang.long.parselong(long.java:372)

    java.lang.long.parselong(long.java:461)

    cn.edu.hactcm.web.action.chapteraction.deleteknowledgepoint(chapteraction.java:199)

這種錯誤可能是因為傳入的值是空值造成的。

錯誤24:

org.hibernate.lazyinitializationexception: failed to lazily initialize a collection of role: cn.edu.hactcm.domain.chapter.knowledgepoints, no session or session was closed

 at org.hibernate.collection.abstractpersistentcollection.throwlazyinitializationexception(abstractpersistentcollection.java:383)

錯誤原因:hibernate 延遲加載的錯誤 failed to lazily initialize a collection of role

解決辦法:

1、設定lazy=false

2、就是使用filter,過濾所有的連結

如果在使用filter的時候,要配置事務處理,否則會導緻session處于隻讀狀态而不能做修改、删除的動作

<web-app>

 <filter>

  <filter-name>hibernatefilter</filter-name>

  <filter-class>

  org.springframework.orm.hibernate.support.opensessioninviewfilter

  </filter-class>

 </filter>

 <filter-mapping>

  <url-pattern>*.do</url-pattern>

 </filter-mapping>

</web-app>

我的解決辦法如:

<set name="knowledgepoints" inverse="true" cascade="all-delete-orphan" lazy="false">

 <key column="chapter_id"/>

 <one-to-many class="knowledgepoint"/>

在後面加了一個lazy="false"屬性。

錯誤25

com.sun.org.apache.xerces.internal.impl.io.malformedbytesequenceexception: invalid byte 2 of 2-byte utf-8 sequence.

分析,這個問題的主要原因是xml檔案中聲明的編碼與xml檔案本身儲存時的編碼不一緻。比如你的聲明是

<?xml version="1.0" encoding="utf-8"?>

但是卻以ansi格式編碼儲存,盡管并沒有亂碼出現,但是xml解析器是無法解析的。

解決辦法就是重新設定xml檔案儲存時的編碼與聲明的一緻

錯誤26

java.lang.illegalargumentexception: id to load is required for loading

出現這樣的錯誤一般是我們的某個字段為null,使用log或system傳回來看看!!