hibernate:a different object with the same identifier value was already associated with the session

本文介绍了一种在使用Hibernate框架时遇到的唯一键冲突错误及其解决办法。该问题发生在调用_saveOrUpdateCollection方法时,原因是session中存在重复的唯一标识符。文章提供了具体的异常堆栈跟踪,并建议在调用此方法前清理session缓存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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(); //清空缓存
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值