不知道是不是之前处理懒加载的问题对session工厂进行了处理,导致了之前没有问题的地方出现了错误.
当修改班级操作时出现了错误
前端错误信息
后台处理以及报错信息
16:37:36,034 ERROR ExceptionMappingInterceptor:38 - a different object with the same identifier value was already associated with the session: [cn.peiying.domain.Classes#128]; nested exception is org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [cn.peiying.domain.Classes#128]
org.springframework.dao.DuplicateKeyException: a different object with the same identifier value was already associated with the session: [cn.peiying.domain.Classes#128]; nested exception is org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [cn.peiying.domain.Classes#128]
出现这个异常的原因:
Hibernate 增删改在 session 中已存在相同 OID(主键) 的对象。比如,先删除,后插入。
这就会报上面的错误。
原来是因为在Hibernate中同一个session内,如果已经有一个对象已经是持久化状态(load进来等),现在构造一个新的PO,和前一个持久化对象拥有相同的持久化标识(identifier),在update的时候,就会抛这个错误。
解决方法
1.不要重新new一个对象,使用load的对象对他进行更改值。
2.如果是hibernate3以上,可以使用session.merge()方法
3.把session中同标识的对象移出(session.evict(user1)),使他成为脱管的状态,然后user2就可以update了
this.getHibernateTemplate().getSessionFactory().getCurrentSession().clear();加上这行代码清除session后,执行通过