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
  • 相关阅读:
    实现ls(课上作业)
    20181217 (2)
    20181217 (1)
    ubuntu开启远程ssh登陆本机功能
    解决ubuntu下Could not get lock的问题
    博客园生成目录结构
    np.mean以及np.std用法
    解决 Could not find a version that satisfies the requirement torch==1.4.0
    github下载ocr模型 windows直接解压出问题
    centos7 连接不上网络解决办法
  • 原文地址:https://www.cnblogs.com/zf-crazy/p/14239355.html
Copyright © 2011-2022 走看看