Java记录唯一性check

发布时间 2023-04-03 17:32:19作者: 浮生半世醉
/**
* 记录唯一性check
*
* @param id 主键
* @param entity 实体记录,必须实现equals()方法才能验证更新的场合
* @param fields 唯一键字段名称
*/
if (entity == null || fields.length == 0) {
  return;
}

try {
  @SuppressWarnings("unchecked")
  T where = (T) entity.getClass().newInstance();
  BeanUtils.copyProperties(entity, where);

  List<String> set = Arrays.asList(fields);
  List<String> uks = new ArrayList<>();
  Class<?> clazz = entity.getClass();
  for (Field fd : clazz.getDeclaredFields()) {
    if (fd.getName().equals("serialVersionUID")) {
    continue;
  }
  fd.setAccessible(true);
  if (set.contains(fd.getName())) {
    uks.add(String.valueOf(fd.get(entity)));
  } else {
    fd.set(where, null);
  }
}

if (uks.isEmpty()) {
  return;
}

  where.setSolrStartTime(null);
  where.setSolrEndTime(null);
  where.setUpdateTime(null);
  where.setCreateTime(null);
  // 查询满足指定字段条件的记录
  List<T> list = findList(where);
  if (id == null && !list.isEmpty()) {
  // 新增,满足条件记录不为空的场合
  throw new I18nException(MSGC000016, StringUtils.join(uks, ","));
}

if (id != null && !list.isEmpty() && !entity.equals(list.get(0))) {
  // 更新,满足的条件记录不是被更新对象的场合(主键不一致)
  throw new I18nException(MSGC000016, StringUtils.join(uks, ","));
}

} catch (I18nException e) {
  throw e;
} catch (Exception e) {
  logger.error(e.getMessage(), e);
}
}

记一次常用的字段唯一性校验封装。