It's fairly straightforward to get Hibernate Validator to validate our annotated beans. Listing 3 presents some demo code for doing exactly this. Let's take a look.
Demo.java, which shows how to use Hibernate Validator to validate annotated beans
package com.wheelersoftware.demos.hibernatevalidator;
import org.hibernate.validator.ClassValidator;
import org.hibernate.validator.InvalidValue;
public final class Demo {
private static ClassValidator<User>
userValidator = new ClassValidator<User>(User.class);
public static void main(String[] args) {
validateUser(createUser());
}
private static User createUser() {
User user = new User();
user.setFirstName("123456789012345678901");
user.setEmail("aol.com");
Address addr = new Address();
addr.setStreet1("");
addr.setCity("Moreno Valley");
addr.setState("CA");
addr.setZip("QWERTY");
user.setAddress(addr);
return user;
}
private static void validateUser(User user) {
InvalidValue[] invalidValues = userValidator.getInvalidValues(user);
for (InvalidValue value : invalidValues) {
System.out.println("========");
System.out.println(value);
System.out.println("message=" + value.getMessage());
System.out.println("propertyName=" + value.getPropertyName());
System.out.println("propertyPath=" + value.getPropertyPath());
System.out.println("value=" + value.getValue());
}
}
}
There are really only a few interesting things happening
here. First, we create a ClassValidator<User>
instance for validating our User beans. We have to
associate the ClassValidator with a type
(here, User) because this is where Hibernate Validator
goes in and reads all the annotations off of the bean class in
question.
Next, we have to create the bean we want to validate. Usually this would come from a user form (for example, a web-based form, or maybe a Swing-based form) though that's not necessarily the case. Here we just create a bean manually, and we intentionally make a lot of the fields invalid so we can see how Hibernate Validator responds.
Finally we make the
call userValidator.getInvalidValues(user). This generates
an array of InvalidValue instances—one for each
validation constraint violation. Let's examine
the InvalidValue class in more detail.