hibernate之Validator使用

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

举例:

entity.

hibernate之Validator使用_第1张图片

Controller层

hibernate之Validator使用_第2张图片

hibernate之Validator使用_第3张图片

 

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  Map validate(T obj){
        Map errMap = null;
        Set> set = validator.validate(obj, Default.class);
        return printMsg(set);
    }

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

    public static  Map printMsg(Set> set){
        Map errMap = null;

        if(Objects.nonNull(set) && set.size() > 0) {
            errMap = new HashMap();
            String property = null;
            for(ConstraintViolation 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文件:

 
            org.hibernate
            hibernate-validator
            6.0.9.Final
       

 

你可能感兴趣的:(Java开发)