Hibernate Validator入门实例

第一次接触Hibernate Validator,

网上搜了一圈,发现很多文章虽然标题相同,

但是内容迥异(分别找到Hibernate Validator、Hibernate ClassValidator、Spring Validator,三者傻傻分不清楚),

很难找到一击即中的例程,经过一圈摸索,现在分享一下我自己整理的必中Hibernate Validator入门实例。

 

首先最少需要引入三个包,分别为

validation-api.jar

hibernate-validator.jar

javax.el.jar (跑main测试需要这个包)

maven依赖:

<dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.1.2.Final</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.el</artifactId>
            <version>3.0.0</version>
        </dependency>


javax-el.jar这个包之所以需要,是因为如果没有这个包,main测试的时候会报错:

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

注:tomcat容器中,不需要javax-el.jar这个包

 

代码:

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.NotNull;
import java.util.Set;

public class Product {

    public static void main(String[] args) {
        Product product = new Product();
        product.setName("name");

        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<Product>> validations = validator.validate(product);
        for (ConstraintViolation<Product> validation : validations) {
            System.out.println(validation.getPropertyPath() + ": "+validation.getMessageTemplate());
        }
    }

    @NotNull(message = "请填写名称")
    private String name;

    @NotNull(message = "请填写数量")
    private String amount;

    @NotNull(message = "请填写价格")
    private String price;

    // getters & setters ...
}

运行结果:

amount: 请填写数量
price: 请填写价格

 

至此,这个简单的hibernate validator的实例就完成了。
接下来再细化一下校验内容就可以了。

 

ref:

http://yamei.blog.51cto.com/4382266/1111120 (Spring Validator和Hibernate Validator)(内含Bean Validation 中内置的 constraint 注释)

http://docs.jboss.org/hibernate/validator/4.2/reference/zh-CN/html_single/#validator-gettingstarted-createproject (Hibernate Validator中文教程)(非常详实)

http://www.tuicool.com/articles/NJVFr2 (Unit / Integration Testing the Bean Validation (JSR-303))

http://stackoverflow.com/questions/24386771/javax-validation-validationexception-hv000183-unable-to-load-javax-el-express

你可能感兴趣的:(Hibernate Validator入门实例)