1 回答
TA贡献1757条经验 获得超8个赞
当尝试验证某些字段在对象列表中是否唯一时,我遇到了同样的问题。我自己的解决方案(我在互联网上没有找到:/ ):
您必须覆盖当前属性节点并使用 添加索引号。例:.addPropertyNode(null).inIterable().atIndex(index)
约束注释:
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueBusinessIndexValidator.class)
public @interface UniqueEntries {
String message() default ValidationMessages.REQUIRED_UNIQUE_INDEX;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
约束验证符:
public class UniqueBusinessIndexValidator implements ConstraintValidator<UniqueEntries, List<HasBusinessIndex>> {
@Override
public boolean isValid(List<HasBusinessIndex> collection, ConstraintValidatorContext context) {
if (collection == null || collection.isEmpty()) {
return true;
}
Map<String, List<Integer>> indexesMap = new HashMap<>();
for (int runner = 0; runner < collection.size(); runner++) {
String businessIndex = collection.get(runner).getBusinessIndex();
if (indexesMap.containsKey(businessIndex)) {
indexesMap.get(businessIndex).add(runner);
} else {
indexesMap.put(businessIndex, new ArrayList<>(List.of(runner)));
}
}
boolean isValid = indexesMap.values().stream().noneMatch(indexes -> indexes.size() > 1);
if (!isValid) {
indexesMap.values()
.stream()
.filter(index -> index.size() > 1)
.forEach(index -> addUniqueBusinessIndexkennungViolation(context, index));
}
return isValid;
}
private void addUniqueBusinessIndexkennungViolation(ConstraintValidatorContext context, List<Integer> indexes) {
for (Integer index : indexes) {
context.buildConstraintViolationWithTemplate(ValidationMessages.REQUIRED_UNIQUE_INDEX)
.addPropertyNode(null)
.inIterable()
.atIndex(index)
.addPropertyNode("businessIndex")
.addConstraintViolation()
.disableDefaultConstraintViolation();
}
}
添加回答
举报