首页 > 学院 > 开发设计 > 正文

Hibernate开发中常见错误总结

2019-11-06 06:49:37
字体:
来源:转载
供稿:网友

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.InvocationTargetExceptionCaused by: org.hibernate.PropertyNotFoundException: Could not find a getter for data in class cn.edu.hactcm.test.hibernate.Event这种错误是把配置文件中的名字写错了的缘故。

5、易错点:在给Date配置属性的时候,需要制定数据类型,并且列名要改一下,应为date为数据库的关键字。

错误6org.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,你又如何划分数据库事务的边界呢?我们将在后续章节解决这些问题。

错误7org.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.ContextLoaderListenerjava.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener清空部署的项目重新启动。

错误914:57:53,624 ERROR ContextLoader:215 - Context initialization failedorg.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.ContextLoaderListenerjava.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory说明配置Web.xml中的<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>需要日志包

错误1119:09:59,958 ERROR ContextLoader:215 - Context initialization failedorg.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.ContextLoaderListenerorg.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 moreCaused 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> {而写下面的时候写成如下的了。@Servicepublic class GenericServiceImpl<T> extends GenericDaoImpl<T> implements GenericService<T> {应该写成:@Transactionalpublic class GenericServiceImpl<T> extends GenericDaoImpl<T> implements GenericService<T> {

错误12org.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的名称导致错误

错误16org.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 fileInvocation 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”

错误17org.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/secondaryAcademyActiondeleteSecondaryAcademy?id=改错办法是:去掉:{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().

错误22java.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:Stacktracesjava.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=false2、就是使用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”属性。

错误25com.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文件保存时的编码与声明的一致

错误26java.lang.IllegalArgumentException: id to load is required for loading出现这样的错误一般是我们的某个字段为null,使用log或system返回来看看!!

 

 

 

 

 

 

原文链接是


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表