Java 验证:验证对象中的对象

Java Validation: Validate an object within an object

我有两个对象:

public class CancelRequest{
 @NotEmpty
 private String id;

 @NotNull
 private BookingDetails;
}

预订详情对象:

public class BookingDetails{
 @NotEmpty
 private String bookingId;
}

我负责验证请求的 class 是 CancelRequestValidator

...
import javax.validation.Validator;
...
public class CancelRequestValidator{
...
public void check(CancelRequest request){
 Set<ConstraintViolation<NorthAmericaCancelTripRequest>> violations = 
validator.validate(request);
...
 }
}

我如何执行验证?

CancelRequest request = new CancelRequest("id",new BookingDetails(""));
CancelValidator validator = new CancelValidator();
violations = validator.check(request);

违规行为中应该有一项指出 bookingId 不能为空,而是认为该对象有效。我需要以这种方式进行验证,因为我需要对此对象执行一些其他业务验证,因此我混合使用了 javax 和自定义验证。

谢谢

要执行嵌套 bean 验证,需要在嵌套对象上使用 @Valid 注解:

public class CancelRequest{
  @NotEmpty
  private String id;

  @NotNull
  @Valid
  private BookingDetails;
}

正如 Eamon Scullion 所说,@Valid 将用于嵌套验证,但不要忘记将 @NotNull 用于对象,如日期,@NotBlank 用于文本字段,@NotEmpty 用于可迭代对象

public class CancelRequest{
    @NotBlank
    private String id;
    

    @NotEmpty
    private List<E> myList;

    @NotNull
    @Valid
    private BookingDetails;
}