3

我有一个对象列表,每个对象都有一封电子邮件,我想验证电子邮件是否在此列表中重复。

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
Father create(@PathVariable String id,
        @Valid @RequestBody Father father) {
   ...
}

父亲会有一份孩子的名单:

private List<Child> childs;

每个孩子都会收到一封电子邮件:

public class Child {
  ...

  @NotEmpty
  private String email;

  ...
}

例如,我想验证是否有一个带有 2 个孩子的请求正文具有相同的电子邮件。

是否有可能或仅在接收和处理有效负载后进行验证?

4

2 回答 2

1

已编辑

要验证子电子邮件列表,您可以创建自定义验证。

我编写了一个自定义验证如下

1-创建名为 ChildEmailValidation 的注释

@Documented
@Constraint(validatedBy = ChildEmailValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ChildEmailValidation {

    String message() default "Duplicate Email";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

2-为ChildEmailValidation

在这部分,您可以编写您的自定义业务进行验证。(你可以写你的算法)

    public class ChildEmailValidator implements ConstraintValidator<ChildEmailValidation, List<Child>> {

    @Override
    public void initialize(ChildEmailValidation constraintAnnotation) {

    }

    @Override
    public boolean isValid(List<Child> childList, ConstraintValidatorContext constraintValidatorContext) {

        //Create empty mailList
        List<String> mailList = new ArrayList<>();

        //Iterate on childList
        childList.forEach(child -> {

            //Checks if the mailList has the child's email
            if (mailList.contains(child.getMail())) {

                  //Found Duplicate email
                  throw new DuplicateEmailException();

            }

            //Add the child's email to mailList (If duplicate email is not found)
            mailList.add(child.getMail());

        });


        //There is no duplicate email
        return true;
      }

    }

3-添加@ChildEmailValidation父亲类

public class Father {

    List<Child> child;

    @ChildEmailValidation
    public List<Child> getChild() {
        return child;
    }

    public void setChild(List<Child> child) {
        this.child = child;
    }
} 

4-@Valid放入fatherDto控制器

@RestController
@RequestMapping(value = "/test/", method = RequestMethod.POST)
public class TestController {

    @RequestMapping(value = "/test")
    public GenericResponse getFamily(@RequestBody @Valid Father fatherDto) {
        // ...
    }

}
于 2020-01-28T22:09:12.833 回答
0

您可以使用基于某些元素@UniqueElements的 Hibernate 注释,您可以在本文档中找到该注释。equals

@UniqueElements
private List<Child> childs;
于 2020-01-28T21:18:26.387 回答