hibernate之Validator使用

Posted helenandyoyo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hibernate之Validator使用相关的知识,希望对你有一定的参考价值。

Validator 作用:后台数据字段校验

举例:

entity.

Controller层

 

Util工具类:

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.groups.Default;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

public class BaseValidatorImpl 

//    private static final Logger log = LoggerFactory.getLogger(BaseValidatorImpl.class);

    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> Map<String, StringBuffer> validate(T obj)
        Map<String, StringBuffer> errMap = null;
        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
        return printMsg(set);
    

    public static <T> Map<String, StringBuffer> validate(Class<T> cls, String s, Object obj)
        Map<String, StringBuffer> errMap = null;
        Set<ConstraintViolation<T>> set = validator.validateValue(cls, s, obj);
        return printMsg(set);
    

    public static <T> Map<String, StringBuffer> printMsg(Set<ConstraintViolation<T>> set)
        Map<String, StringBuffer> errMap = null;

        if(Objects.nonNull(set) && set.size() > 0) 
            errMap = new HashMap<String, StringBuffer>();
            String property = null;
            for(ConstraintViolation<T> cv: set)
                property = cv.getPropertyPath().toString();
                if(errMap.get(property) != null)
                    errMap.get(property).append("," +cv.getMessage());
                else
                    StringBuffer stringBuffer = new StringBuffer();
                    stringBuffer.append(cv.getMessage());
                    errMap.put(property, stringBuffer);
                
            
        
        return errMap;
    

pom文件:

 <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.9.Final</version>
        </dependency>

 

以上是关于hibernate之Validator使用的主要内容,如果未能解决你的问题,请参考以下文章

Spring/Spring boot JSR-303验证框架 之 hibernate-validator

Spring/Spring boot JSR-303验证框架 之 hibernate-validator

spring和hibernate整合之---java.lang.ClassNotFoundException: javax.el.ELManager 大坑

Hibernate Validator 使用详解

使用 Hibernate Validator 进行实体验证的问题

spring 项目中使用 hibernate validator验证输入参数