Code in controller -
@PostMapping("/employees")
public Employee saveEmployee(@Valid @RequestBody Employee employee) {
return employeeService.saveEmployee(employee);
}
Entity Object -
@NotNull(message = "Department must not be null")
@Column(name = "department")
private String department;
Suppose I pass an item with a null department field. @NonNull will throw an exception in that case. But I have seen @Valid being used for the same purpose. Can somebody elaborate why @Valid needs to be used in addition to @NonNull?
CodePudding user response:
If you omit the @Valid
Spring will omit the validation on the web layer. Which basically means your controller, will not trigger validation. Validation is done by the RequestMappingHandlerAdapter
when an @Valid(adted)
annotation is found on an @ModelAttribute
or @RequestBody
annotated method argument.
JPA will also use a configured validator and trigger validation as well. So a validation exception will be thrown upon writing into the database. You can disable this with spring.jpa.properties.javax.persistence.validation.mode=none
in your application.properties
(or the YAML equivalent). When disabling both no validation will be done. In that case you only hope is a database constraint that the column isn't allowed to be null
.
So validation is still done but the location where the validation is done is different. Due to the difference you will also get a different exception.
You have to wonder do you really want to do this somewhere upon persisting the entity with the risk of having executed some complex/time consuming business logic, or quickly upon submission of the form.
CodePudding user response:
So that the object can be validated in the Controller layer you need @Valid
(or @Validated
) to trigger its validation.
You can read more about this on the following online resources:
- https://www.baeldung.com/spring-boot-bean-validation
- https://www.baeldung.com/spring-valid-vs-validated
On which you can read:
Of course, the most relevant part is the use of the @Valid annotation. When Spring Boot finds an argument annotated with @Valid, it automatically bootstraps the default JSR 380 implementation — Hibernate Validator — and validates the argument.