I would like to make a field validation without persisting data by using Spring Boot and Hibernate Validator.
public class RoomDto {
private long id;
@Expose
private int beds;
@Expose
private double size;
@Expose
@NotNull
private String flatBasicStringDto;
}
I am parsing a DTO from JSON by using GSON:
RoomDto guestRoom = this.jsonParser.read(RoomDto.class, "/files/input/room.json");
I would like to get an error when flatBasicStringDto is missing in the JSON file.
I have tried many configurations but nothing works so far.
spring.jpa.properties.javax.persistence.validation.group.pre-persist=javax.validation.groups.Default
Any ideas how to deal with this issue?
You can use method level validation using @valid annotation. However, you need your DI container to hook in with the validation framework. A comprehensive example using spring is at http://www.mkyong.com/spring-mvc/spring-3-mvc-and-jsr303-valid-example/.
If you dont want to use a DI containter, you can use something like this to get the validation errors:
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<RoomDto>> errors = validator.validate(guestRoom);