hibernate validater

1、bean定义时,在需要校验的field加上校验的注解

 1 package entrance;
 2 
 3 import javax.validation.constraints.Max;
 4 import javax.validation.constraints.Pattern;
 5 
 6 public class Bean
 7 {
 8     /**
 9      * 支付完成时间
10      **/
11     @Max(value = 14, message = "max val is 14")
12     private Integer payTime;
13 
14     /**
15      * 状态
16      **/
17     @Pattern(regexp = "0[0123]", message = "状态只能为00或01或02或03")
18     private String status;
19 
20     public Integer getPayTime() {
21         return payTime;
22     }
23 
24     public void setPayTime(Integer payTime) {
25         this.payTime = payTime;
26     }
27 
28     public String getStatus() {
29         return status;
30     }
31 
32     public void setStatus(String status) {
33         this.status = status;
34     }
35 }

2、添加hibernate-validater依赖

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>4.3.2.Final</version>
    </dependency>
    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>1.1.0.Final</version>
    </dependency>

3、增加校验工具类

package entrance;

import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import org.hibernate.validator.HibernateValidator;

public class HibernateValidater
{
    //快速失败模式,只要有一个验证失败就返回失败
    private static Validator validator = Validation
        .byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();

    public static <T> void validate(T objToBeValidate) throws Exception
    {
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(objToBeValidate);

        // 抛出检验异常
        if (constraintViolations.size() > 0)
        {
            throw new Exception(constraintViolations.iterator().next().getMessage());
        }
    }
}

4、手动or通过aop触发校验

package entrance;

public class Main
{
    public static void main(String[] args) throws Exception
    {
        Bean bean = new Bean();
        bean.setPayTime(15);
        bean.setStatus("00");
        HibernateValidater.validate(bean);

        bean.setStatus("01");
        HibernateValidater.validate(bean);

        bean.setStatus("02");
        HibernateValidater.validate(bean);

        bean.setStatus("03");
        HibernateValidater.validate(bean);


    }
}

 

posted @ 2018-05-26 07:06  hxy_has_been_used  阅读(343)  评论(0编辑  收藏  举报