Preface
Validating data is a common task that occurs throughout all application layers, from the presentation to the persistence layer. Often the same validation logic is implemented in each layer which is time consuming and error-prone. To avoid duplication of these validations, developers often bundle validation logic directly into the domain model, cluttering domain classes with validation code which is really metadata about the class itself.

JSR 380 - Bean Validation 2.0 - defines a metadata model and API for entity and method validation. The default metadata source are annotations, with the ability to override and extend the meta-data through the use of XML. The API is not tied to a specific application tier nor programming model. It is specifically not tied to either web or persistence tier, and is available for both server-side application programming, as well as rich client Swing application developers.

Hibernate Validator is the reference implementation of this JSR 380. The implementation itself as well as the Bean Validation API and TCK are all provided and distributed under the Apache Software License 2.0.
Hibernate Validator 6 and Bean Validation 2.0 require Java 8 or later.
1. Getting started
This chapter will show you how to get started with Hibernate Validator, the reference implementation (RI) of Bean Validation. For the following quick-start you need:
-
A JDK 8
-
An Internet connection (Maven has to download all required libraries)
1.1. Project set up
In order to use Hibernate Validator within a Maven project, simply add the following dependency to your pom.xml:
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.9.Final</version>
</dependency>
This transitively pulls in the dependency to the Bean Validation API (javax.validation:validation-api:2.0.1.Final
).
1.1.1. Unified EL
Hibernate Validator requires an implementation of the Unified Expression Language (JSR 341) for evaluating dynamic expressions in constraint violation messages (see Section 4.1, “Default message interpolation”). When your application runs in a Java EE container such as JBoss AS, an EL implementation is already provided by the container. In a Java SE environment, however, you have to add an implementation as dependency to your POM file. For instance you can add the following dependency to use the JSR 341 reference implementation:
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b09</version>
</dependency>
For environments where one cannot provide a EL implementation Hibernate Validator is offering aSection 12.9, “ |
1.1.2. CDI
Bean Validation defines integration points with CDI (Contexts and Dependency Injection for Java TM EE, JSR 346). If your application runs in an environment which does not provide this integration out of the box, you may use the Hibernate Validator CDI portable extension by adding the following Maven dependency to your POM:
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator-cdi</artifactId>
<version>6.0.9.Final</version>
</dependency>
Note that adding this dependency is usually not required for applications running on a Java EE application server. You can learn more about the integration of Bean Validation and CDI in Section 11.3, “CDI”.
1.1.3. Running with a security manager
Hibernate Validator supports running with a security manager being enabled. To do so, you must assign several permissions to the code bases of Hibernate Validator, the Bean Validation API, Classmate and JBoss Logging and also to the code base calling Bean Validation. The following shows how to do this via a policy file as processed by the Java default policy implementation:
grant codeBase "file:path/to/hibernate-validator-6.0.9.Final.jar" {
permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
permission java.lang.RuntimePermission "accessDeclaredMembers";
permission java.lang.RuntimePermission "setContextClassLoader";
permission org.hibernate.validator.HibernateValidatorPermission "accessPrivateMembers";
// Only needed when working with XML descriptors (validation.xml or XML constraint mappings)
permission java.util.PropertyPermission "mapAnyUriToUri", "read";
};
grant codeBase "file:path/to/validation-api-2.0.1.Final.jar" {
permission java.io.FilePermission "path/to/hibernate-validator-6.0.9.Final.jar", "read";
};
grant codeBase "file:path/to/jboss-logging-3.3.2.Final.jar" {
permission java.util.PropertyPermission "org.jboss.logging.provider", "read";
permission java.util.PropertyPermission "org.jboss.logging.locale", "read";
};
grant codeBase "file:path/to/classmate-1.3.4.jar" {
permission java.lang.RuntimePermission "accessDeclaredMembers";
};
grant codeBase "file:path/to/validation-caller-x.y.z.jar" {
permission org.hibernate.validator.HibernateValidatorPermission "accessPrivateMembers";
};
1.1.4. Updating Hibernate Validator in WildFly
The WildFly application server contains Hibernate Validator out of the box. In order to update the server modules for Bean Validation API and Hibernate Validator to the latest and greatest, the patch mechanism of WildFly can be used.
You can download the patch file from SourceForge or from Maven Central using the following dependency:
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator-modules</artifactId>
<version>6.0.9.Final</version>
<classifier>wildfly-12.0.0.Final-patch</classifier>
<type>zip</type>
</dependency>
We also provide a patch for WildFly 11.0.0.Final:
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator-modules</artifactId>
<version>6.0.9.Final</version>
<classifier>wildfly-11.0.0.Final-patch</classifier>
<type>zip</type>
</dependency>
Having downloaded the patch file, you can apply it to WildFly by running this command:
$JBOSS_HOME/bin/jboss-cli.sh patch apply hibernate-validator-modules-6.0.9.Final-wildfly-12.0.0.Final-patch.zip
In case you want to undo the patch and go back to the version of Hibernate Validator originally coming with the server, run the following command:
$JBOSS_HOME/bin/jboss-cli.sh patch rollback --reset-configuration=true
1.1.5. Running on Java 9
As of Hibernate Validator 6.0.9.Final, support for Java 9 and the Java Platform Module System (JPMS) is experimental. There are no JPMS module descriptors provided yet, but Hibernate Validator is usable as automatic modules.
These are the module names as declared using the Automatic-Module-Name
header:
-
Bean Validation API:
java.validation
-
Hibernate Validator core:
org.hibernate.validator
-
Hibernate Validator CDI extension:
org.hibernate.validator.cdi
-
Hibernate Validator test utilities:
org.hibernate.validator.testutils
-
Hibernate Validator annotation processor:
org.hibernate.validator.annotationprocessor
These module names are preliminary and may be changed when providing real module descriptors in a future release.
When using Bean Validation XML descriptors (META-INF/validation.xml and/or constraint mapping files), the java.xml.bind
module must be enabled. Do so by appending --add-modules java.xml.bind
to your java invocation.
When using Hibernate Validator with CDI, be careful to not enable the Instead, add the full JSR 250 API to the unnamed module (i.e. the classpath), e.g. by pulling in the javax.annotation:javax.annotation-api dependency (there already is a transitive dependency to the JSR 250 API when depending on org.hibernate.validator:hibernate-validator-cdi). If you need to enable the |
1.2. Applying constraints
Let’s dive directly into an example to see how to apply constraints.
package org.hibernate.validator.referenceguide.chapter01;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Car {
@NotNull
private String manufacturer;
@NotNull
@Size(min = 2, max = 14)
private String licensePlate;
@Min(2)
private int seatCount;
public Car(String manufacturer, String licencePlate, int seatCount) {
this.manufacturer = manufacturer;
this.licensePlate = licencePlate;
this.seatCount = seatCount;
}
//getters and setters ...
}
The @NotNull
, @Size
and @Min
annotations are used to declare the constraints which should be applied to the fields of a Car instance:
-
manufacturer
must never benull
-
licensePlate
must never benull
and must be between 2 and 14 characters long -
seatCount
must be at least 2
You can find the complete source code of all examples used in this reference guide in the Hibernate Validator source repository on GitHub. |
1.3. Validating constraints
To perform a validation of these constraints, you use a Validator
instance. Let’s have a look at a unit test for Car
:
package org.hibernate.validator.referenceguide.chapter01;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CarTest {
private static Validator validator;
@BeforeClass
public static void setUpValidator() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void manufacturerIsNull() {
Car car = new Car( null, "DD-AB-123", 4 );
Set<ConstraintViolation<Car>> constraintViolations =
validator.validate( car );
assertEquals( 1, constraintViolations.size() );
assertEquals( "must not be null", constraintViolations.iterator().next().getMessage() );
}
@Test
public void licensePlateTooShort() {
Car car = new Car( "Morris", "D", 4 );
Set<ConstraintViolation<Car>> constraintViolations =
validator.validate