• JPA的merge对联合唯一索引无效(代码库)


    问题

      JPA的merge()操作 是合并的意思,就是当保存的实体时,根据主键id划分,如果已存在,那么就是更新操作,如果不存在,就是新增操作

      但是这个仅针对 主键id 划分,对联合唯一索引 无效,两次更新同一条语句还是会报错:

      Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
    com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1-1' for key 'UK_bing'

    解决

    有个简单的办法,就是先判断是否有这条数据,然后再决定是更新、还是增加,如下:

    @Override
    public void mergeCollection(Collection collection) {
        String hql = "select count(1) from Collection where userId = ?1 and topicId =?2";
        Query query = em.createQuery(hql)
                .setParameter(1, collection.getUserId())
                .setParameter(2, collection.getTopicId());
        Long num = (Long) query.getSingleResult();
    
        if (num > 0) {
            String hql2 = "update Collection set status = ?3 where userId = ?1 and topicId =?2";
            Query query2 = em.createQuery(hql2)
                    .setParameter(1, collection.getUserId())
                    .setParameter(2, collection.getTopicId())
                    .setParameter(3, collection.getStatus());
            query2.executeUpdate();
        } else {
            em.merge(collection);
        }
    }

     原创文章,欢迎转载,转载请注明出处!

  • 相关阅读:
    css3实现文本渐变
    元组--购物车实战
    js事件冒泡
    openssl生成v3版自签证书
    linux中可以在哪些地方增加环境变量
    linux下如何找到USB转串口
    linux下通过shell命令测试串口
    CANopen协议
    ubuntu使用虚拟can(vcan)
    移植python3到flash有限的arm
  • 原文地址:https://www.cnblogs.com/acm-bingzi/p/jpa_merge.html
Copyright © 2020-2023  润新知