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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持呐喊教程。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。