Hibernate開發中常見錯誤總結
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
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返回來看看!!
給我老師的人工智慧教程打call!http://blog.csdn.net/jiangjunshow
我們對Markdown編輯器進行了一些功能拓展與語法支援,除了標準的Markdown編輯器功能,我們增加了如下幾點新功能,幫助你用它寫部落格:- 全新的介面設計 ,將會帶來全新的寫作體驗;
- 在創作中心設定你喜愛的程式碼高亮樣式,Markdown 將程式碼片顯示選擇的高亮樣式 進行展示;
- 增加了 圖片拖拽 功能,你可以將本地的圖片直接拖拽到編輯區域直接展示;
- 全新的 KaTeX數學公式 語法;
- 增加了支援甘特圖的mermaid語法1 功能;
- 增加了 多螢幕編輯 Markdown文章功能;
- 增加了 焦點寫作模式、預覽模式、簡潔寫作模式、左右區域同步滾輪設定 等功能,功能按鈕位於編輯區域與預覽區域中間;
- 增加了 檢查列表 功能。
功能快捷鍵
撤銷:Ctrl/Command + Z
重做:Ctrl/Command + Y
加粗:Ctrl/Command + B
斜體:Ctrl/Command + I
標題:Ctrl/Command + Shift + H
無序列表:Ctrl/Command + Shift + U
有序列表:Ctrl/Command + Shift + O
檢查列表:Ctrl/Command + Shift + C
插入程式碼:Ctrl/Command + Shift + K
插入連結:Ctrl/Command + Shift + L
插入圖片:Ctrl/Command + Shift + G
合理的建立標題,有助於目錄的生成
直接輸入1次#,並按下space後,將生成1級標題。
輸入2次#,並按下space後,將生成2級標題。
以此類推,我們支援6級標題。有助於使用TOC
語法後生成一個完美的目錄。
如何改變文字的樣式
強調文字 強調文字
加粗文字 加粗文字
標記文字
刪除文字
引用文字
H2O is是液體。
210 運算結果是 1024.
插入連結與圖片
連結: link.
圖片:
帶尺寸的圖片:
當然,我們為了讓使用者更加便捷,我們增加了圖片拖拽功能。
如何插入一段漂亮的程式碼片
去部落格設定頁面,選擇一款你喜歡的程式碼片高亮樣式,下面展示同樣高亮的 程式碼片
.
// An highlighted block var foo = 'bar';
生成一個適合你的列表
- 專案
- 專案
- 專案
- 專案
- 專案1
- 專案2
- 專案3
- 計劃任務
- 完成任務
建立一個表格
一個簡單的表格是這麼建立的:
專案 | Value |
---|---|
電腦 | $1600 |
手機 | $12 |
導管 | $1 |
設定內容居中、居左、居右
使用:---------:
居中
使用:----------
居左
使用----------:
居右
第一列 | 第二列 | 第三列 |
---|---|---|
第一列文字居中 | 第二列文字居右 | 第三列文字居左 |
SmartyPants
SmartyPants將ASCII標點字元轉換為“智慧”印刷標點HTML實體。例如:
TYPE | ASCII | HTML |
---|---|---|
Single backticks | 'Isn't this fun?' |
‘Isn’t this fun?’ |
Quotes | "Isn't this fun?" |
“Isn’t this fun?” |
Dashes | -- is en-dash, --- is em-dash |
– is en-dash, — is em-dash |
建立一個自定義列表
- Markdown
- Text-to- HTML conversion tool
- Authors
- John
- Luke
如何建立一個註腳
一個具有註腳的文字。2
註釋也是必不可少的
Markdown將文字轉換為 HTML。
KaTeX數學公式
您可以使用渲染LaTeX數學表示式 KaTeX:
Gamma公式展示 是通過尤拉積分
你可以找到更多關於的資訊 LaTeX 數學表示式here.
新的甘特圖功能,豐富你的文章
gantt
dateFormat YYYY-MM-DD
title Adding GANTT diagram functionality to mermaid
section 現有任務
已完成 :done, des1, 2014-01-06,2014-01-08
進行中 :active, des2, 2014-01-09, 3d
計劃一 : des3, after des2, 5d
計劃二 : des4, after des3, 5d
- 關於 甘特圖 語法,參考 這兒,
UML 圖表
可以使用UML圖表進行渲染。 Mermaid. 例如下面產生的一個序列圖::
這將產生一個流程圖。:
- 關於 Mermaid 語法,參考 這兒,
FLowchart流程圖
我們依舊會支援flowchart的流程圖:
- 關於 Flowchart流程圖 語法,參考 這兒.
匯出與匯入
匯出
如果你想嘗試使用此編輯器, 你可以在此篇文章任意編輯。當你完成了一篇文章的寫作, 在上方工具欄找到 文章匯出 ,生成一個.md檔案或者.html檔案進行本地儲存。
匯入
如果你想載入一篇你寫過的.md檔案或者.html檔案,在上方工具欄可以選擇匯入功能進行對應副檔名的檔案匯入,
繼續你的創作。
註腳的解釋 ↩︎