Issue
I'm learning java and spring boot and I am trying to validate a controller parameter which was bound from json.
I've got simple Entity:
@Getter
@Setter
class Resource {
@NotBlank
String uri;
}
Which I want to persist through the following controller:
@BasePathAwareController
public class JavaResourcePostController {
private final ResourceRepository repository;
public JavaResourcePostController(ResourceRepository repository) {
this.repository = repository;
}
@RequestMapping(value = "/resources", method = RequestMethod.POST)
ResponseEntity<Resource> create(
@Valid @RequestBody Resource resource
) {
repository.save(resource);
return ResponseEntity.ok(resource);
}
}
My understanding is that the resource argument should be valid when entering the method. But posting an empty uri
field does not trigger the validation of the method. it does however get triggered in the hibernate validation in repository.save()
Why does the @Valid
annotation on the argument not ensure I get a validated entity?
Solution
You need to add @Validated
to your controller class.
Answered By - geobreze