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

时间:2023-03-09 08:03:57
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);
}
}

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