Search code examples
javaspringspring-bootjacksonhibernate-validator

Validation nested models in spring boot


I have a problem with validation of nested models, look:

class A{
   @NotNull
   Integer i;
   B b;
}
class B{
   @NotNull
   Integer j;
}

In spring controller:
@Valid @RequestBody...

It properly validate i, but not validate j. How to force Spring to validate arbitraly deep ?

And second thing:
Is it possible to do following validation: Object of class 'A' is proper only and only if exactly one of i an j is null.

class A{
   Integer i;
   Integer j;
}

Solution

  • Object graph validation is supported and you have to annotate B b with @Valid like below.

    class A{
      @NotNull
      Integer i;
      @Valid
      B b;
    }
    

    Please refer https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=5.3#section-object-graph-validation for more details.

    For second part of you question, you can create a custom Validator class. You would also need a custom annotation for that Validator. You can check the details at documentation page here. A sample for custom Validator is here.