11

I'm trying to validate a DTO (formModel, whatever term you prefer) which is a bit layered (inheritance and dependencies to other classes).

Is it possible to get the following configuration of models to work:

public abstract class A {

    @NotNull
    private String fieldA1;

    @NotNull
    @Size(min = 2, max = 30)
    private String fieldA2;

    // ... and so on

}


public class B extends A {

    @NotNull
    private String fieldB1;

    @NotNull
    private Xyz fieldB2;

    // and so on
}


public class Xyz {

    @NotNull
    private String fieldXyz1;

    // etc..
}

Spring rest controller:

@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity addCustomer(@RequestBody @Valid B customerDto, BindingResult bindingResult) {
// controller logic here
}

The problem is: only constraint annotations that seem to "work" are those on the parent class A. I submit a request with bad fields in the class A, bindingResult.hasErrors() returns true. If I submit a request with bad fields in classes B or Xyz, bindingResult.hasErrors() is false and the controller just goes on behaving like the request is ok. Any ideas why?

6
  • 1
    If you want to validate object fields, use @Valid annotation. beanvalidation.org/1.0/spec/#d0e991 Commented Jun 18, 2018 at 7:59
  • That fixes my object field, but what to do about fieldB1? Commented Jun 18, 2018 at 8:06
  • The following link : stackoverflow.com/questions/21841202/… Commented Jun 18, 2018 at 9:15
  • Are you sure fieldB1 validation is not working? That should work... maybe you are setting empty string... in that case, use @NotBlank (if you are using Hibernate's bean validation implementation). Commented Jun 18, 2018 at 16:24
  • yes i'm most positive :) I've already refactored this structure to just have @Valid dependency objects instead of inheritance. Still, would like to know why this is happening Commented Jun 19, 2018 at 7:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.