Search code examples
javabean-validationhibernate-validator

How to force Hibernate Validator to validate fields recursively(cascaded)?


I have the following model:

class EmailWrapper {

    @Email
    private String subscriptionEmail;

    private MyClass myClass;
    //get and set
}


class MyClass {
    @Size(min = 12)
    private String str = "short";
    //get and set
}

and following code:

EmailWrapper emailWrapper = new EmailWrapper();
emailWrapper.setSubscriptionEmail("qq@gmail.com");
emailWrapper.setMyClass(new MyClass());
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<EmailWrapper>> constraintViolations = validator.validate(emailWrapper);
System.out.println(constraintViolations.size());

As You can see that emailWrapper.myClass.str violates the @Size(min = 12)

but I see 0 in console. How to fix this?


Solution

  • Replace

    private MyClass myClass;
    

    by

    @Valid
    private MyClass myClass;