Hibernate Validator : Getting Started

What is Hibernate Validator? Any advantages?
Are there any new features in Java 8?
How to define Constraints for a Model?
How to create a Customized Constraint?
How to validate the Constraints and get the Violations?

Star_coin-30 This tutorial’s purpose is to introduce  Hibernate Validator in simple words and to help you setup quickly an example. If you want to strengthen your knowledge you can’t find better than the Official Documentation.

code-source This tutorial’s code source is in letsprog Github.


question_80px What is Hibernate Validator?

Hibernate Validator is an implementation of Java eXtensions Validation API (Java built-in). Its purpose is to declare and to validate constraints (over a bean, an object fields, a method arguments) using built-in or customized annotations, without messing with your code. Exemple:

moneda_de_oro Hibernate Validator advantages

  • You can validate your object when you want to. For example, Car unbrandedCar = new Car(“”) won’t show any problem until you decide to validate the object : validator.validate(unbrandedCar).
  • Hibernate Validator works as your reporter, and not as a decider in your place. After validating the instance, Hibernate Validator will report to you the non-respected rules. And it’s up to you to judge the instance as rejected or not.
  • Hibernate Validator let you customize the rules and so you can create your own annotation representing the rule.
  • Hibernate Validator let you categorize the rules into errors/warnings/information/… So, it’s not always about errors 🙂
  • The best of is that Hibernate Validator won’t throw to you an exception if a rule is not respected, but it will rather construct a Set of Violations.

Thank you JBoss family, you have given us such another cute baby…!

hibernate validator


reqs Tutorial Requirements

Requirements :

question_80px Do we really need to have Java 8 for this tutorial?

Yes. Java 8 has added in its Javax Validation API support for customized constraints for Generic Types (parameterized types). Example :


Maven Dependencies

Add the following dependencies to your pom.xml file:

Since we want to make a Java 8 compliant project, configure Maven Compiler Plugin as follows :

Remark : In case you didn’t include javax.el-api dependency, you would get this expection when trying to get an instance of the constraints validator :


Constrained Model

The Car class :

  • The brand field is annotated by @NotEmpty, that means brand cannot be null nor an empty string “”. However, it can be filled by ”   ” (3 spaces).

The Person class :

  • The name field is annotated by @NotBlank, so it cannot be null nor an empty string “”, nor spaces! And so after trimming the value, its size should be > 0.
  • The emailAddress field, besides that it is @NotBlank, it is annotated @Pattern in which we have defined the regular expression which an email address should respect.
  • The age field has multiple constraints. It should not be null (@NotNull), and has a customized constraint @PositiveNumberConstraint which imposes the age to be a positive number. Moreover, we have defined a customized category of the Constraint Violation : payload=Severity.Error.class. We will discover in the next section how to define customized constraint with customized severity.
  • The luckyNumbers field has a parameterized type, that is a List of String. As we are using Java 8, we can add a rule over a type parameters. Adding the customized constraint @PositiveNumberConstraint, a lucky number shouldn’t be a negative one 🙂
  • The car field shouldn’t be null (@NotNull). Being annotated by @Valid, this field will be validated in cascade. And so any constrainted sub-field will be validated, too. In our case, it is the subfield car.brand if not empty.

Customized Validator

Defining the Customized Constraint Annotation

The PositiveNumberConstraint customized annotation :

  • @Target : To specify the kind of “things” we want to make validatable. I have only mentionned the necessary ones :
    • ElementType.FIELD : To make a field validatable.
    • ElementType.TYPE_USE : To make a Type parameter validatable, such . If this annotation is missing, you will get the compilation error The annotation @PositiveNumberConstraint is disallowed for this location.

hibernate_validator_type_use_necessary

  • @Constraint : To specify the implementation which will override the predicate of verifying the validity of the thing.

Defining the Customized Constraint logic

The PositiveNumberConstraintValidator class  :

This class must implement the Generic Interface ConstraintValidator. This interface must have as the first parameter the Constraint Annotation (PositiveNumberConstraint), and as the second parameter the Constrained Data Type (String).

The validation logic goes into the overriden method isValid(..).

Defining the Customized Constraint Severity

 


Validation

close-the-end-super-mario-s

Using the Default Java eXtention Validation API implementation

Let’s create 2 persons, one with valid data and the other one no :

  • From line 30 to 33 : Assigning bad values to the second person, causing constraints violation.
  • Line 36 : As we are including in our project only Hibernate Validator as the Java eXtention Validation API implementation, we are sure that Hibernate Validator will be taken as the default implementation to construct the Validator Factory.
  • Line 37 : Getting the Validator instance using the created factory.
  • Line 40 : Here we do finally validate one of the persons instance, giving as a return a Set of Constraint Violations.
  • Line 53 : Checking the Constrained Violation Severity.

Specifying the Java eXtention Validation API implementation

You only need to specify the Validation Provider as following to constrauct the Validator Factory :


Testing

super_mario_end

Run your main class and check the log :