zoukankan      html  css  js  c++  java
  • hibernate中执行saveOrUpdate()时的异常

    1.问题描述:
    将业务代码放在service层,执行saveOrUpdate()时,出现对象已经存在的异常。
    Exception in thread"main"org.hibernate.NonUniqueObjectException:
    a different object with the same identifier value was already exit。

    2.怀疑数据库有两条id重复的数据? 实时证明,数据库只有一条 原因: hibernate中,在service服务调用saveOrUpdate时, 因为session中有相同对象,抛出有重复对象的异常,实际上数据库也只有唯一一条数据,按道理应该执行update的。
    源码:
    /**
    * Attempts to check whether the given key represents an entity already loaded within the
    * current session.
    * @param object The entity reference against which to perform the uniqueness check.
    * @throws HibernateException
    */
    public void checkUniqueness(EntityKey key, Object object) throws HibernateException {
    Object entity = getEntity(key); //在hibernate session中获取对象
    if ( entity == object ) {
    throw new AssertionFailure( "object already associated, but no entry was found" );
    }
    if ( entity != null ) {//如果对象存在就抛出异常....session就不能存在相同对象?????
    throw new NonUniqueObjectException( key.getIdentifier(), key.getEntityName() );
    }
    }
    解决方案: 
    Object obj
    = super.hibernateTemplate().merge(object)
    super.hibernateTemplate().saveOrUpdate(obj)
    将对象与session中的对象合并,返回合并后的对象进行update

    public void updateAll(Collection<T> entities) {
    for(T e : entities){
    T merge = super.getHibernateTemplate().merge(e);
    super.getHibernateTemplate().saveOrUpdate(merge);
    }
    }
    参考:https://blog.csdn.net/baidu_41437297/article/details/84953946
  • 相关阅读:
    自此KYang独一人
    根本不存在 DIV + CSS 布局这回事转
    释德扬,少林大师教你简易健身法
    只让指定的机器连接SQLServer服务器
    Visual Studio 2005 IDE模板丢失的解决方法
    asp.net 未能加载视图状态
    如何控制触发器递归
    4G相关标准UMB/LTE/WiMAX介绍
    Linq To Sql 项目从Beta迁移到RTM注意事项
    保护眼睛的windows窗口颜色
  • 原文地址:https://www.cnblogs.com/zf-crazy/p/14239355.html
Copyright © 2011-2022 走看看