Hibernate.orgCommunity Documentation
This chapter will show you how to get started with Hibernate Validator, the reference implementation (RI) of Bean Validation. For the following quickstart you need:
A JDK >= 5
An Internet connection (Maven has to download all required libraries)
A properly configured remote repository. Add the following to your
settings.xml
:
Example 1.1. Configuring the JBoss Maven repository
<repositories> <repository> <id>jboss-public-repository-group</id> <url>https://repository.jboss.org/nexus/content/groups/public-jboss</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories>
More information about settings.xml
can
be found in the Maven
Local Settings Model.
Hibernate Validator uses JAXB for XML parsing. JAXB is part of the Java Class Library since Java 6 which means that if you run Hibernate Validator with Java 5 you will have to add additional JAXB dependencies. Using Maven you have to add the following dependencies:
<dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.1.12</version> </dependency>
if you are using the SourceForge package you find the
necessary libraries in the lib/jdk5
directory. In
case you are not using the XML configuration you can also disable it
explicitly by calling
Configuration.ignoreXmlConfiguration()
during
ValidationFactory
creation. In this case the JAXB
dependencies are not needed.
Start by creating new Maven project using the Maven archetype plugin as follows:
Example 1.2. Using Maven's archetype plugin to create a sample project using Hibernate Validator
mvn archetype:generate -DarchetypeGroupId=org.hibernate \ -DarchetypeArtifactId=hibernate-validator-quickstart-archetype \ -DarchetypeVersion=4.2.0.Final \ -DarchetypeRepository=http://repository.jboss.org/nexus/content/groups/public-jboss/ \ -DgroupId=com.mycompany \ -DartifactId=hv-quickstart
Maven will create your project in the directory hv-quickstart. Change into this directory and run:
mvn test
Maven will compile the example code and run the implemented unit tests. Let's have a look at the actual code.
From version 4.2.0.Beta2, the maven command mvn
archetype:create
will be no longer supported and will fail.
You should use the command described in the above listing. If you want
more details, look at Maven
Archetype plugin page.
Open the project in the IDE of your choice and have a look at the
class Car
:
Example 1.3. Class Car annotated with constraints
package com.mycompany;
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 ...
}
@NotNull
, @Size
and
@Min
are so-called constraint annotations, that we
use to declare constraints, which shall be applied to the fields of a
Car
instance:
manufacturer shall never be null
licensePlate shall never be null and must be between 2 and 14 characters long
seatCount shall be at least 2.
To perform a validation of these constraints, we use a
Validator
instance. Let's have a look at the
CarTest
class:
Example 1.4. Class CarTest showing validation examples
package com.mycompany;
import static org.junit.Assert.*;
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;
public class CarTest {
private static Validator validator;
@BeforeClass
public static void setUp() {
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("may not be null", constraintViolations.iterator().next().getMessage());
}
@Test
public void licensePlateTooShort() {
Car car = new Car("Morris", "D", 4);
Set<ConstraintViolation<Car>> constraintViolations =
validator.validate(car);
assertEquals(1, constraintViolations.size());
assertEquals("size must be between 2 and 14", constraintViolations.iterator().next().getMessage());
}
@Test
public void seatCountTooLow() {
Car car = new Car("Morris", "DD-AB-123", 1);
Set<ConstraintViolation<Car>> constraintViolations =
validator.validate(car);
assertEquals(1, constraintViolations.size());
assertEquals("must be greater than or equal to 2", constraintViolations.iterator().next().getMessage());
}
@Test
public void carIsValid() {
Car car = new Car("Morris", "DD-AB-123", 2);
Set<ConstraintViolation<Car>> constraintViolations =
validator.validate(car);
assertEquals(0, constraintViolations.size());
}
}
In the setUp()
method we get a
Validator
instance from the
ValidatorFactory
. A
Validator
instance is thread-safe and may be reused
multiple times. For this reason we store it as field of our test class. We
can use the Validator
now to validate the different
car instances in the test methods.
The validate()
method returns a set of
ConstraintViolation
instances, which we can iterate
in order to see which validation errors occurred. The first three test
methods show some expected constraint violations:
The @NotNull
constraint on manufacturer
is violated in manufacturerIsNull()
The @Size
constraint on licensePlate is
violated in licensePlateTooShort()
The @Min
constraint on seatCount is
violated in seatCountTooLow()
If the object validates successfully,
validate()
returns an empty set.
Note that we only use classes from the package javax.validation from the Bean Validation API. As we don't reference any classes of the RI directly, it would be no problem to switch to another implementation of the API, should that need arise.
That concludes our 5 minute tour through the world of Hibernate Validator. Continue exploring the code examples or look at further examples referenced in Chapter 10, Further reading. To deepen your understanding of Hibernate Validator just continue reading Chapter 2, Validation step by step. In case your application has specific validation requirements have a look at Chapter 3, Creating custom constraints.
Copyright © 2009 - 2011 Red Hat, Inc. & Gunnar Morling