Hibernate Validator Annotations Example

Welcome to Hibernate Validator Annotations Example tutorial. Today, i will show you Hibernate Validator API with a full working example. Hibernate Validator is a JSR 303 implementation for bean validation. The way to work with hibernate framework is to define constraints for java bean fields, and then, validating the bean.

Hibernate Validator features

  • Defining validation data using annotation and/or XML.
  • Full object validation, including inner objects using recursion
  • Create customized constraints and validators.
  • Customized error messages.
  • Define groups(profiles).
  • Create a Traversable Resolver.

Other interesting posts you may like

Create project directory structure
In this Hibernate Validator Annotations Example, we will create java project with final directory structure:

Hibernate Validator Annotations Example

Maven dependencies
We provide the required Hibernate and MySQL dependency in pom.xml like this:

Let’s look into the above dependencies:
We need to add JSR303 and Hibernate Validator dependencies in pom.xml to use them.

However, Hibernate Validator requires Expression Language API dependencies (JSR 341) for evaluating dynamic expressions in constraint violation messages. Required dependencies are

If you run the application on server application such as JBoss, you can skip over this dependencies because it’s already provided.

Create bean validation
Create a Student class and add some validation constraints to it. You also refer to other validation constraints

As you see above, we can also provide custom error message for any validation. If not the hibernate built-in error message will be used.

Hibernate Validator Custom Error Messages
We can create our custom error messages too, all we need is to push ValidationMessages.properties file into the classpath.


Hibernate validator also support localization, in that case the file names follow the pattern of bundle name with language code and country code, for example ValidationMessages_en_US.properties

The property name for message is fully classified annotation name with message at the end, you can easily figure out from above examples.

Create a test program
In this Hibernate Validator Annotations Example tutorial, we create a main class in which we save a student object missed some fields. Then we validate that object by using Hibernate validator API.

Run above main and produce the output like below

That’s it on the tutorial Hibernate Validator Annotations Example

Download complete source code, please click link below

HibernateValidatorAnnotationsExample.zip (322 downloads)

Leave a Comment


Please share it if you found this useful
Hide Buttons