hibernate validate 手动验证集合/验证树形类结构

教程分享 > Java教程 (5178) 2023-03-28 11:29:14

提示:文末提供demo项目下载!!!

一、hibernate validate项目创建

validate项目
 

二、hibernate validate依赖说明

$title(pom.xml)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo-manual-validate</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo-manual-validate</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.16.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.4</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
重点配置:
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.16.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.4</version>
        </dependency>

三、hibernate validate验证工具编写

$title(ValidateUtils.java)
package com.example.demomanualvalidate.util;

import org.springframework.util.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

public class ValidateUtils {

    public static String validate(Object obj) {
        // 用于存储验证后的错误信息
        StringBuffer buffer = new StringBuffer(64);

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

        if (obj!=null&& obj instanceof Collection){
            Collection collection=(Collection)obj;
            for (Object ob:collection){
                String res=validate(ob);
                if (!StringUtils.isEmpty(res)){
                    buffer.append(res);
                    buffer.append(",");
                }
            }
        }

        //对象字段中含有集合的处理
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field:fields){
            field.setAccessible(true);
            Object fv=getFieldValueByName(field.getName(),obj);
            if (fv!=null&&fv instanceof Collection){
                String res=validate(fv);
                if (!StringUtils.isEmpty(res)){
                    buffer.append(res);
                    buffer.append(",");
                }

            }
        }
        // 验证某个对象,其实也可以只验证其中的某一个属性的
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj);
        Iterator<ConstraintViolation<Object>> iter = constraintViolations.iterator();
        while (iter.hasNext()) {
            String message = iter.next().getMessage()+",";
            buffer.append(message);
        }
        if(buffer.length()>0)
            return buffer.toString().substring(0, buffer.toString().length()-1);
        return buffer.toString();
    }

    /**
     * 根据属性名获取属性值
     * */
    public static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[] {});
            Object value = method.invoke(o, new Object[] {});
            return value;
        } catch (NoSuchMethodException e){
//            System.out.println("验证字段get方法未找到");
            return null;
        } catch (InvocationTargetException e) {
			//忽略方法内部错误
			return null;
		} catch (Exception e) {
           throw new RuntimeException("验证过程获取属性值错误",e);
        }
    }
}

四、hibernate validate验证数据模型创建

$title(DogFood.java)
package com.example.demomanualvalidate.model;

import javax.validation.constraints.NotEmpty;

/**
 * 狗粮
 */
public class DogFood {
    @NotEmpty(message = "狗粮名称不能为空")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
$title(Dog.java)
package com.example.demomanualvalidate.model;

import javax.validation.constraints.NotNull;
import java.util.List;

public class Dog {
    public Dog(String name) {
        this.name = name;
    }

    @NotNull(message = "宠物名称不能为空")
    private String name;

    private List<DogFood> foods;

    public List<DogFood> getFoods() {
        return foods;
    }

    public void setFoods(List<DogFood> foods) {
        this.foods = foods;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
 
$title(Persion.java)
package com.example.demomanualvalidate.model;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;

public class Persion {
    public Persion(String name, List<Dog> dogs) {
        this.name = name;
        this.dogs = dogs;
    }

    @NotEmpty(message = "用户名不能为空")
    private String name;

    @NotNull(message = "必须有宠物狗")
    private List<Dog> dogs;//拥有的宠物狗

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Dog> getDogs() {
        return dogs;
    }

    public void setDogs(List<Dog> dogs) {
        this.dogs = dogs;
    }
}

五、hibernate validate验证测试

$title(Test.java)
package com.example.demomanualvalidate;

import com.example.demomanualvalidate.model.Dog;
import com.example.demomanualvalidate.model.DogFood;
import com.example.demomanualvalidate.model.Persion;
import com.example.demomanualvalidate.util.ValidateUtils;

import java.util.Arrays;

public class Test {
    public static void main(String[] args) {
        //-----0
        Persion p0=new Persion("", null);
        String failValue=ValidateUtils.validate(p0);
        System.out.println("错误信息0:"+failValue);

        Dog d1=new Dog(null);
        Persion p1=new Persion("", Arrays.asList(new Dog[]{d1}));
        failValue=ValidateUtils.validate(p1);
        System.out.println("错误信息1:"+failValue);

        //-----2
        DogFood df=new DogFood();
        d1.setFoods(Arrays.asList(new DogFood[]{df}));

        Persion p2=new Persion("", Arrays.asList(new Dog[]{d1}));
        failValue=ValidateUtils.validate(p2);
        System.out.println("错误信息2:"+failValue);

        //---GOOD
        Dog d=new Dog("阿三");
        Persion p=new Persion("小左",Arrays.asList(new Dog[]{d}));
        failValue=ValidateUtils.validate(p);
        System.out.println("错误信息:"+failValue);

    }
}


执行结果截图:
执行demo结果


从输出结果来看,已经实现了hibernate validate树形验证,有任何问题欢迎下方评论区留言讨论。
 

项目下载地址 :demo-manual-validate.zip

https://www.leftso.com/article/600.html

相关文章
提示:文末提供demo项目下载!!!一、hibernate validate项目创建​ 二、hibernate validate依赖说明$title(pom.xml) &lt;?xml vers...
Spring Boot validation整合hibernate validator实现数据验证,Spring Boot validation使用说明,Spring Boot validat...
Spring Boot 2.0 hibernate validate 版本冲突导致验证无效,HV000030: No validator could be found for constrain...
hibernate validator 正则表达式报错HV000030: No validator could be found for constraint 'javax.validation...
@Validated和@Valid注解的使用和区别注解使用框架@Valid 使用Hibernate validation的时候使用;@Validated 仅Spring Validator校验机...
项目升级到springboot之后,参数校验的注解报错,经过与原项目对比,发现spring-boot-starter-web的依赖项已经去除了依赖原版会有如下: &lt;dependency&g...
spring validate 验证List集合演示用类User/Addressimport lombok.Data; import javax.validation.constraint...
在这个Spring5教程中,学习创建Spring 5 MVC Web应用程序,处理表单提交,集成hibernate连接到后端数据库,以及添加用于输入表单字段验证的hibernate验证器。
通过之前的一些文章spring boot 2.3 hibernate validate框架未引入-左搜 (leftso.com)Spring boot 参数分组校验-左搜 (leftso.com...
在本文中,我们将讨论如何使用Bean Validation 2.0(JSR-380)定义和验证方法约束。在前面的文章中,我们讨论了JSR-380及其内置的注释,以及如何实现属性验证。在这里,我们...
Value '4320' is not valid duration.Checks Spring boot application .properties configuration files...
在这篇快速文章中,我们将介绍使用标准框架 - JSR 380(也称为Bean Validation 2.0)来验证Java bean的基础知识。当然,在大多数应用程序中验证用户输入是超常见的需求...
Hibernate Search 入门配置及简单实用,在本文中,我们将讨论Hibernate Search的基础知识,如何配置它,并且我们将实现一些简单的查询。
1.概要在本Spring boot教程中,我们将学习如何验证发送到PUT/POST API请求的数据BODY