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编辑器功能,我们增加了如下几点新功能,帮助你用它写博客:
  1. 全新的界面设计 ,将会带来全新的写作体验;
  2. 在创作中心设置你喜爱的代码高亮样式,Markdown 将代码片显示选择的高亮样式 进行展示;
  3. 增加了 图片拖拽 功能,你可以将本地的图片直接拖拽到编辑区域直接展示;
  4. 全新的 KaTeX数学公式 语法;
  5. 增加了支持甘特图的mermaid语法1 功能;
  6. 增加了 多屏幕编辑 Markdown文章功能;
  7. 增加了 焦点写作模式、预览模式、简洁写作模式、左右区域同步滚轮设置 等功能,功能按钮位于编辑区域与预览区域中间;
  8. 增加了 检查列表 功能。

功能快捷键

撤销: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.

图片: Alt

带尺寸的图片: Alt

当然,我们为了让用户更加便捷,我们增加了图片拖拽功能。

如何插入一段漂亮的代码片

博客设置页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的 代码片.

// An highlighted block var foo = 'bar'; 

生成一个适合你的列表

  • 项目
    • 项目
      • 项目
  1. 项目1
  2. 项目2
  3. 项目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公式展示 Γ ( n ) = ( n 1 ) ! n N \Gamma(n) = (n-1)!\quad\forall n\in\mathbb N 是通过欧拉积分

Γ ( z ) = 0 t z 1 e t d t &ThinSpace; . \Gamma(z) = \int_0^\infty t^{z-1}e^{-t}dt\,.

你可以找到更多关于的信息 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文件,在上方工具栏可以选择导入功能进行对应扩展名的文件导入,
继续你的创作。


  1. mermaid语法说明 ↩︎

  2. 注脚的解释 ↩︎

猜你喜欢

转载自blog.csdn.net/jdtugfcg/article/details/83895270