Search code examples
javavalidationhibernate-validatorspring-framework-beansannotated-pojos

@NotNull clarification for JSR-303 validation


I have a POJO annotated with JSR-303 annotations. Some of its attributes are other POJOs. I would like the inner POJOs to be @Valid, only if they are not null. But if they're null it's OK. Unfortunately I'm not succeding in doing this, so Java returns me the error for the inner POJOs attribute if they're null.

@AllArgsConstructor @NoArgsConstructor @Data
class OuterPojo{
    @NotBlank private String attributeA;
    @Valid    private InnerPojo attributeB;
}

@AllArgsConstructor @NoArgsConstructor @Data
class InnerPojo{
    @NotBlank private String attributeC;
    @NotNull  private Double attributeD;
}

I want an outerPojo to be valid if:

  1. attributeA is not-null and attributeB is null;
  2. attributeB is not-null and attributeB is not-null and valid.

So I would like the constraints on the attributes of inner pojo to be respected only if inner pojo is not null.

I've tried adding @Nullable to attributeB with no effect. How can I solve this?


Solution

  • Just adding @Valid should mean valid if not null. Section 3.5.1 of the JSR 303: Bean Validation specification says "Null references are ignored" when validating the object graph.

    I verified this using Hibernate Validator 6.0.2.Final and this simple test class.

    public class Main {
        public static void main(String[] args) {
            OuterPojo outer = new OuterPojo("some value", null);
            ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
            Validator v = factory.getValidator();
            Set<ConstraintViolation<OuterPojo>> errors = v.validate(outer);
            for (ConstraintViolation<OuterPojo> violation : errors) {
                System.out.println(violation.getMessage());
            }
        }
    }