Today I would like to share some basic uses cases of JSR 303 annotations and programmatic validation support. Let us start with first one.
1. Assume you are expecting Person object to be passed to you business logic layer, just typical Java bean with few properties.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | package org.example; public class Person { private String firstName; private String lastName; public void setFirstName( String firstName ) { this .firstName = firstName; } public String getFirstName() { return firstName; } public void setLastName( String lastName ) { this .lastName = lastName; } public String getLastName() { return lastName; } } |
1 2 3 4 5 6 7 8 9 10 | package org.example; import org.hibernate.validator.constraints.NotBlank; public class Person { @NotBlank private String firstName; @NotBlank private String lastName; ... } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | package org.example; import java.util.HashSet; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import javax.validation.groups.Default; public class ValidatorUtil { private final ValidatorFactory factory; public ValidatorUtil() { factory = Validation.buildDefaultValidatorFactory(); } public < T > void validate( final T instance ) { final Validator validator = factory.getValidator(); final Set< ConstraintViolation< T > > violations = validator .validate( instance, Default. class ); if ( !violations.isEmpty() ) { final Set< ConstraintViolation< ? > > constraints = new HashSet< ConstraintViolation< ? > >( violations.size() ); for ( final ConstraintViolation< ? > violation: violations ) { constraints.add( violation ); } throw new ConstraintViolationException( constraints ); } } } |
1 2 | final Person person = new Person(); new ValidatorUtil().validate( person ); |
2. Assume you are expecting Department object to be passed to you business logic containing at least one (valid!) person. Let me skip the details and present the final solution here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | package org.example; import java.util.Collection; import javax.validation.Valid; import org.hibernate.validator.constraints.NotEmpty; public class Department { @NotEmpty @Valid private Collection< Person > persons; public void setPersons( Collection< Person > persons ) { this .persons = persons; } public Collection< Person > getPersons() { return persons; } } |
There are just a lot of other use case out there which Hibernate Validator is able to handle out of the box: @Min, @Man, @Email, @Url, @Range, @Length, @Pattern, ... This post is just a starting point ...