What configuration is needed to use annotations from javax.validation.constraints
like @Size
, @NotNull
, etc.? Here\'s my code:
You would have to call a Validator on the Entity if you want to validate it. Then you will get a set of ConstraintViolationException, which basically show for which field/s of your Entity there is a constraint violation and what exactly was it. Maybe you can also share some of the code you expect to validate your entity.
An often used technique is to do validation in @PrePersist and rollback transaction if using multiple data modifications during transaction or do other actions when you get a validation exception.
Your code should go like this:
@PrePersist
public void prePersist(SomeEntity someEntity){
Validator validator = Validation.buildDefaultValidatorFactory.getValidator();
Set<ConstraintViolation<SomeEntity>> = validator.validate(someEntity);
//do stuff with them, like notify client what was the wrong field, log them, or, if empty, be happy
}
You need to add @Valid to each member variable, which was also an object that contained validation constraints.
For JSR-303 bean validation to work in Spring, you need several things:
<mvc:annotation-driven />
validation-api-1.0.0.GA.jar
(looks like you already have that)hibernate-validator-4.1.0.Final.jar
@Valid
, and then include a BindingResult
in the method signature to capture errors. Example:
@RequestMapping("handler.do")
public String myHandler(@Valid @ModelAttribute("form") SomeFormBean myForm, BindingResult result, Model model) {
if(result.hasErrors()) {
...your error handling...
} else {
...your non-error handling....
}
}
If you are using lombok then, you can use @NonNull annotation insted. or Just add the javax.validation dependency in pom.xml file.
In my case, I was using spring boot version 2.3.0. When I changed my maven dependency to use 2.1.3 it worked.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
</dependencies>
in my case i had a custom class-level constraint that was not being called.
@CustomValidation // not called
public class MyClass {
@Lob
@Column(nullable = false)
private String name;
}
as soon as i added a field-level constraint to my class, either custom or standard, the class-level constraint started working.
@CustomValidation // now it works. super.
public class MyClass {
@Lob
@Column(nullable = false)
@NotBlank // adding this made @CustomValidation start working
private String name;
}
seems like buggy behavior to me but easy enough to work around i guess