JSR 303:如何验证带注释的对象的集合?

cam*_*cam 45 java jsr hibernate-validator bean-validation

是否可以验证JSR 303中的对象集合 - Jave Bean Validation,其中集合本身没有任何注释,但包含的元素是什么?

例如,由于第二个人的名称为空,是否可能导致约束违规:

List<Person> people = new ArrayList<Person>();
people.add(new Person("dave"));
people.add(new Person(null));

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<List<Person>>> validation = validator.validate(people);
Run Code Online (Sandbox Code Playgroud)

sou*_*ica 61

是的,只需添加@Valid到集合中.

以下是Hibernate Validator Reference的一个示例.

public class Car {
  @NotNull
  @Valid
  private List<Person> passengers = new ArrayList<Person>();
}
Run Code Online (Sandbox Code Playgroud)

这是标准的JSR-303行为.参见规范的 3.1.3节.


dez*_*r10 20

你,也可以添加@NotEmpty到集合中.

public class Car {
  @NotEmpty(message="At least one passenger is required")
  @Valid
  private List<Person> passengers = new ArrayList<Person>();
}
Run Code Online (Sandbox Code Playgroud)

这将确保至少有一名乘客,并且@Valid注释确保每个Person对象都经过验证