1. 问题
调用_saveOrUpdateCollection方法报错:
方法:
public void _saveOrUpdateCollection(Collection<T> collection) {
try {
getHibernateTemplate().saveOrUpdateAll(collection);
} catch (Exception e) {
throw new RuntimeException("保存更新失败..." + e.getMessage());
}
}
报错异常:
java.lang.RuntimeException: 保存更新失败...a different object with the same identifier value was already associated with the session:[com.app.zf.itsm.web.cmdb.entity.Itsm_ci_parts#40288a245ed0cbfd015ed1b5cb070008]; nested exception is org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.app.zf.itsm.web.cmdb.entity.Itsm_ci_parts#40288a245ed0cbfd015ed1b5cb070008]
at com.app.core.dao.impl.BaseDaoImpl._saveOrUpdateCollection(BaseDaoImpl.java:209) ~[classes/:?]
2. 原因
在调用_saveOrUpdateCollection时,session中存在着两条或两条以上某一个字段是相同的数据,而这相同的字段恰恰是有唯一键约束(比如主键),这就造成了以上的报错。而造成问题的原因很可能是在调用这一方法之前,查询了数据库相同的表数据,导致了session缓存中有了数据,进而引起了唯一键冲突。
3. 解决方法
在查询完引起冲突的数据库表之后,清理session缓存,或者调用_saveOrUpdateCollection方法之前,清理session缓存。
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
session.clear(); //清空缓存