Hibernate.orgCommunity Documentation
本章将会告诉你如何使用Hibernate Validator, 在开始之前,你需要准备好下面的环境:
A JDK >= 6
网络连接 ( Maven需要通过互联网下载所需的类库)
A properly configured remote repository. Add the following to your settings.xml
:
例 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.
In order to use Hibernate Validator within an existing Maven project, simply add the following dependency to your pom.xml
:
例 1.2. Maven dependency of Hibernate Validator
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.2.Final</version> </dependency>
Alternatively, you can start by creating a sample project using Hibernate Validator's Quickstart Maven archetype as follows:
例 1.3. 使用Maven archetype 插件来创建一个简单的基于Hibernate Validator的项目
mvn archetype:generate -DarchetypeGroupId=org.hibernate \ -DarchetypeArtifactId=hibernate-validator-quickstart-archetype \ -DarchetypeVersion=4.3.2.Final \ -DarchetypeRepository=http://repository.jboss.org/nexus/content/groups/public-jboss/ \ -DgroupId=com.mycompany \ -DartifactId=hv-quickstart
Maven 将会把你的项目创建在hv-quickstart目录中. 进入这个目录并且执行:
mvn test
Maven will compile the example code and run the implemented unit tests. Let's have a look at the actual code in the next section.
For the purposes of logging, Hibernate Validator uses the JBoss Logging API. This is an abstraction layer which supports several known logging solutions (e.g. log4j or the logging framework provided by the JDK) as implementation. Just add your preferred logging library to the classpath and all log requests from Hibernate Validator will automatically be delegated to that logging provider.
Alternatively, you can explicitely specify a provider using the system property org.jboss.logging.provider
. Supported values currently are jboss
, jdk
, log4j
and slf4j
.
在你喜欢的IDE中打开这个项目中的Car
类:
例 1.4. 带约束性标注(annotated with constraints)的Car 类
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
就是上面所属的约束性标注( constraint annotations), 我们就是使用它们来声明约束, 例如在Car
的字段中我们可以看到:
manufacturer永远不能为null
licensePlate永远不能为null,并且它的值字符串的长度要在2到14之间
seatCount的值要不能小于2
我们需要使用Validator
来对上面的那些约束进行校验. 让我们来看看CarTest
这个类:
例 1.5. 在CarTest中使用校验
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());
}
}
在setUp()
方法中,我们通过ValidatorFactory
得到了一个Validator
的实例. Validator
是线程安全的,并且可以重复使用, 所以我们把它保存成一个类变量. 现在我们可以在test方法中使用这个validator的实例来校验不同的car实例了.
validate()
方法会返回一个set的ConstraintViolation
的实例的集合, 我们可以通过遍历它来查看有哪些验证错误. 前面三个测试用例显示了一些预期的校验约束:
在manufacturerIsNull()
中可以看到manufacturer违反了@NotNull
约束
licensePlateTooShort()
中的licensePlate违反了@Size
约束
而seatCountTooLow()
中则导致seatCount违反了@Min
约束
如果一个对象没有校验出问题的话,那么validate()
会返回一个空的set对象.
注意,我们只使用了Bean Validation API中的package javax.validation中的类, 并没有直接调用参考实现中的任何类,所以, 没有任何问题如果切换到其他的实现.
That concludes our 5 minute tour through the world of Hibernate Validator. Continue exploring the code examples or look at further examples referenced in 第 10 章 进一步阅读. To deepen your understanding of Hibernate Validator just continue reading 第 2 章 Validation step by step. In case your application has specific validation requirements have a look at 第 3 章 创建自己的约束规则.
版权 © 2009 - 2011 Red Hat, Inc. & Gunnar Morling