欢迎来到代码驿站!

当前位置:首页 >

JPA merge联合唯一索引无效问题解决方案

时间:2020-09-19 13:00:23|栏目:|点击:

问题

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);
  }
}

上一篇:SpringMvc自动装箱及GET请求参数原理解析

栏    目:

下一篇:R语言ggplot2边框背景去除的实现

本文标题:JPA merge联合唯一索引无效问题解决方案

本文地址:http://www.codeinn.net/misctech/5181.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有