{{ !articles[0].partner.isSponsoringArticle ? "Platinum" : "Portal" }} Partner

Hibernate Validator 4: Model Validation Made Easy

Version 4.0 of Hibernate Validator has been released recently, which is now the reference implementation for JSR 303: Bean Validation. The real benefit to this release is that you can now annotate your domain model with various constraints, rather than needing to write your model validation yourself. For people who want to take a model driven development approach, this is a big time saver.

The Hibernate Validator documentation has the perfect image to illustrate this. Rather than having custom validation at each step along the way, the domain model contains all the constraints, and therefore validation rules exist in one single place.


There are a number of build in constraint annotations available such as those you'd expect - @notNull, @notEmpty, @min, and @max.

public class Driver extends Person {
@Min(value = 18, message = "You have to be 18 to drive a car", groups = DriverChecks.class)
public int age

There are also some others like @email, which checks if the string is an email format and @future, which validates a date to ensure that it is in the future. A useful list of the built-in constraints is provided here. Naturally, your domain model may have constraints that don't exist in this list - there's instructions on how to create your own constraint annotations here

New In Hibernate Validator

Hibernate Validator 4 is based on a new codebase, with tons of useful features. Any of the constraints that you use can be put together to compose new constraints. Violation messages can be attached to your constraints, and you can return more than one of these messages if you wish. 

Because the framework complies to the Bean Validation JSR, it integrates with Java Persistence API 2 and Java Server Faces 2. As you use other Java libraries that take advantage of JSR 303, that code can also be aware of the constraints that you specify. 

This framework looks great, and the importance of a common approach to bean validation cannot be understated. A single approach cuts down on the amount of duplicate code - the more frameworks that use this JSR for their validation, the better. 


{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks