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
org.hibernate.HibernateException: No CurrentSessionContext configured!
?at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:683)
?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>
錯誤7
不能自動創建表
需要加上<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
java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
說明配置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
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)
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)
?at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:61)
?at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:877)
?... 40 more
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)
這種錯誤的原因是:在寫事務的時候?
@Transactional
@SuppressWarnings("unchecked")
public class GenericDaoImpl<T> implements GenericDao<T> {
而寫下面的時候寫成如下的了。
@Service
public class GenericServiceImpl<T> extends GenericDaoImpl<T> implements GenericService<T> {
應該寫成:
@Transactional
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中配置了如下參數:
<property name="current_session_context_class">thread</property>
將這一句刪除后就沒有問題了。
錯誤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>
<property name="breakAfterAcquireFailure">
??? <value>false</value>
</property>
- 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>
??<filter-name>hibernateFilter</filter-name>
??<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"/>
</set>
在后面加了一個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返回來看看!!
from:?http://blog.csdn.net/tototuzuoquan/article/details/8043564
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Hibernate开发中常见错误总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一台电脑上同启动两个Tomcat的方式,
- 下一篇: echarts散点图使用