In this tutorial we're going to learn how to get started with Hibernate Validator, which as its name suggests is a validation framework associated with the Hibernate project. This article is really a follow-up to my earlier article on using the Bean Validation Framework (part of the larger Spring Modules project), which is a competing framework that seems to have lost the battle for Spring's "preferred validation provider" status to Hibernate Validator. Both Uri Boness (in an e-mail correspondence) and Juergen Hoeller (at SpringOne) agreed that people should start moving toward Hibernate Validator since that will eventually support the emerging JSR 303 standard.
Hibernate Validator is nice because it (like the Bean Validation
Framework) supports declarative validation
via Java
5 annotations. Let's say you create a bean class, like
an Account or a PurchaseOrder or
whatever. With Hibernate Validator you can attach validation
annotations to the bean properties and that will define the validation
constraints for the bean. Moreover, unlike earlier approaches to
validation (such as Struts Validation), Hibernate Validator isn't tied
to the web tier, and so if you want to validate your beans from within
your service beans, or within your DAOs, or even just before you ORM
them into your database, no sweat. You can do just that.
Anyway, for now we're just going to look at some of the basics: how to specify annotation constraints and how to check for constraint violations. We're not going to worry about integrating Hibernate Validator with Spring's native validation framework (so that, for instance, we might render Hibernate Validator error messages out using Spring Web MVC taglibs) though I'll probably write another article on that sometime in the future if people are interested.
For this article we're using Java 5 or higher (we need Java 5 annotations) and Hibernate Validator 3.1.0. For your convenience I've created a Maven 2 project that you can download.
OK, let's jump into some examples of annotated bean classes.