Does javax validation work with inheritance?

1.7k Views Asked by At

I am trying to validate a model, which is inheriting from another model and this parent model has @NotBlank annotation to validate a parameter. But this validation is bypassed in the controller which is accepting a list of child class objects.

The code snippet should give a fair idea of the scenario

public abstract class A {
  @NotBlank
  private String name;
}

public class B extends A {
  private String type;
}

@PostMapping(consumes= MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity saveRoles(@Valid @RequestBody List<B> roles){
   // ideally it should not land here if request has blank name. But it seems to land here.
   // logic 
}

The request body -

[
    {
        "name": "",
        "type": "system"
    }
]

1

There are 1 best solutions below

3
donquih0te On

You trying to validate the collection itself, but not the collection elements. Try this:

@PostMapping(consumes= MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity saveRoles(@RequestBody List<@Valid B> roles){
  
}