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

时间:2022-05-22 15:34:34

问题

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'

解决

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@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);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/acm-bingzi/p/jpa_merge.html