【hibernate validator】(五)分组约束

首发博客地址

https://blog.zysicyj.top/

一、请求组

1. 人组

package org.hibernate.validator.referenceguide.chapter05;
public class Person {
    @NotNull
    private String name;
    public Person(String name) {
        this.name = name;
    }
    // getters and setters ...
}

2. 驱动组

public class Driver extends Person {
    @Min(
            value = 18,
            message = "You have to be 18 to drive a car",
            groups = DriverChecks.class
    )
    public int age
;
    @AssertTrue(
            message = "You first have to pass the driving test",
            groups = DriverChecks.class
    )
    public boolean hasDrivingLicense
;
    public Driver(String name) {
        super( name );
    }
    public void passedDrivingTest(boolean b) {
        hasDrivingLicense = b;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

3. 汽车组

public class Car {
    @NotNull
    private String manufacturer;
    @NotNull
    @Size(min = 2, max = 14)
    private String licensePlate;
    @Min(2)
    private int seatCount;
    @AssertTrue(
            message = "The car has to pass the vehicle inspection first",
            groups = CarChecks.class
    )
    private boolean passedVehicleInspection
;
    @Valid
    private Driver driver;
    public Car(String manufacturer, String licencePlate, int seatCount) {
        this.manufacturer = manufacturer;
        this.licensePlate = licencePlate;
        this.seatCount = seatCount;
    }
    public boolean isPassedVehicleInspection() {
        return passedVehicleInspection;
    }
    public void setPassedVehicleInspection(boolean passedVehicleInspection) {
        this.passedVehicleInspection = passedVehicleInspection;
    }
    public Driver getDriver() {
        return driver;
    }
    public void setDriver(Driver driver) {
        this.driver = driver;
    }
    // getters and setters ...
}

4. 使用验证组

// create a car and check that everything is ok with it.
Car car = new Car( "Morris""DD-AB-123"2 );
Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );
assertEquals( 0, constraintViolations.size() );
// but has it passed the vehicle inspection?
constraintViolations = validator.validate( car, CarChecks.class );
assertEquals( 1, constraintViolations.size() );
assertEquals(
        "The car has to pass the vehicle inspection first",
        constraintViolations.iterator().next().getMessage()
);
// let's go to the vehicle inspection
car.setPassedVehicleInspection( true );
assertEquals( 0, validator.validate( car, CarChecks.class ).size() );
// now let's add a driver. He is 18, but has not passed the driving test yet
Driver john = new Driver( "John Doe" );
john.setAge( 18 );
car.setDriver( john );
constraintViolations = validator.validate( car, DriverChecks.class );
assertEquals( 1, constraintViolations.size() );
assertEquals(
        "You first have to pass the driving test",
        constraintViolations.iterator().next().getMessage()
);
// ok, John passes the test
john.passedDrivingTest( true );
assertEquals( 0, validator.validate( car, DriverChecks.class ).size() );
// just checking that everything is in order now
assertEquals(
        0, validator.validate(
        car,
        Default.class,
        CarChecks.class,
        DriverChecks.class
).size()
)
;

二、组继承(🐮)

  • 定义一个超级跑车
public class SuperCar extends Car {
    @AssertTrue(
            message = "Race car must have a safety belt",
            groups = RaceCarChecks.class
    )
    private boolean safetyBelt
;
    // getters and setters ...
}
import javax.validation.groups.Default;
public interface RaceCarChecks extends Default {
}
  • 使用组继承
// create a supercar and check that it's valid as a generic Car
SuperCar superCar = new SuperCar( "Morris""DD-AB-123"1  );
assertEquals( "must be greater than or equal to 2", validator.validate( superCar ).iterator().next().getMessage() );
// check that this supercar is valid as generic car and also as race car
Set<ConstraintViolation<SuperCar>> constraintViolations = validator.validate( superCar, RaceCarChecks.class );
assertThat( constraintViolations ).extracting( "message" ).containsOnly(
        "Race car must have a safety belt",
        "must be greater than or equal to 2"
);

三、定义组序列(🐮)

  • 定义序列组
import javax.validation.GroupSequence;
import javax.validation.groups.Default;
@GroupSequence({ Default.classCarChecks.classDriverChecks.class })
public interface OrderedChecks 
{
}
  • 使用序列组
Car car = new Car( "Morris""DD-AB-123"2 );
car.setPassedVehicleInspection( true );
Driver john = new Driver( "John Doe" );
john.setAge( 18 );
john.passedDrivingTest( true );
car.setDriver( john );
assertEquals( 0, validator.validate( car, OrderedChecks.class ).size() );

四、重新定义默认的组顺序

@GroupSequence

  • 定义一个具有重定义的默认组的类
@GroupSequence({ RentalChecks.classCarChecks.classRentalCar.class })
public class RentalCar extends Car 
{
    @AssertFalse(message = "The car is currently rented out", groups = RentalChecks.class)
    private boolean rented
;
    public RentalCar(String manufacturer, String licencePlate, int seatCount) {
        super( manufacturer, licencePlate, seatCount );
    }
    public boolean isRented() {
        return rented;
    }
    public void setRented(boolean rented) {
        this.rented = rented;
    }
}
public interface RentalChecks {
}
  • 使用重新定义的默认组
RentalCar rentalCar = new RentalCar( "Morris""DD-AB-123"2 );
rentalCar.setPassedVehicleInspection( true );
rentalCar.setRented( true );
Set<ConstraintViolation<RentalCar>> constraintViolations = validator.validate( rentalCar );
assertEquals( 1, constraintViolations.size() );
assertEquals(
        "Wrong message",
        "The car is currently rented out",
        constraintViolations.iterator().next().getMessage()
);
rentalCar.setRented( false );
constraintViolations = validator.validate( rentalCar );
assertEquals( 0, constraintViolations.size() );

@GroupSequenceProvider

  • 实现和使用默认组序列
public class RentalCarGroupSequenceProvider
        implements DefaultGroupSequenceProvider<RentalCar
{
    @Override
    public List<Class<?>> getValidationGroups(RentalCar car) {
        List<Class<?>> defaultGroupSequence = new ArrayList<Class<?>>();
        defaultGroupSequence.add( RentalCar.class );
        if ( car != null && !car.isRented() ) {
            defaultGroupSequence.add( CarChecks.class );
        }
        return defaultGroupSequence;
    }
}
@GroupSequenceProvider(RentalCarGroupSequenceProvider.class)
public class RentalCar extends Car 
{
    @AssertFalse(message = "The car is currently rented out", groups = RentalChecks.class)
    private boolean rented
;
    public RentalCar(String manufacturer, String licencePlate, int seatCount) {
        super( manufacturer, licencePlate, seatCount );
    }
    public boolean isRented() {
        return rented;
    }
    public void setRented(boolean rented) {
        this.rented = rented;
    }
}

五、组转换(🐮)

  • 必须集合@Valid哦,否则报错
public class Driver {
    @NotNull
    private String name;
    @Min(
            value = 18,
            message = "You have to be 18 to drive a car",
            groups = DriverChecks.class
    )
    public int age
;
    @AssertTrue(
            message = "You first have to pass the driving test",
            groups = DriverChecks.class
    )
    public boolean hasDrivingLicense
;
    public Driver(String name) {
        this.name = name;
    }
    public void passedDrivingTest(boolean b) {
        hasDrivingLicense = b;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    // getters and setters ...
}
@GroupSequence({ CarChecks.classCar.class })
public class Car 
{
    @NotNull
    private String manufacturer;
    @NotNull
    @Size(min = 2, max = 14)
    private String licensePlate;
    @Min(2)
    private int seatCount;
    @AssertTrue(
            message = "The car has to pass the vehicle inspection first",
            groups = CarChecks.class
    )
    private boolean passedVehicleInspection
;
    @Valid
    @ConvertGroup(from = Default.classto = DriverChecks.class)
    private Driver driver
;
    public Car(String manufacturer, String licencePlate, int seatCount) {
        this.manufacturer = manufacturer;
        this.licensePlate = licencePlate;
        this.seatCount = seatCount;
    }
    public boolean isPassedVehicleInspection() {
        return passedVehicleInspection;
    }
    public void setPassedVehicleInspection(boolean passedVehicleInspection) {
        this.passedVehicleInspection = passedVehicleInspection;
    }
    public Driver getDriver() {
        return driver;
    }
    public void setDriver(Driver driver) {
        this.driver = driver;
    }
    // getters and setters ...
}
// create a car and validate. The Driver is still null and does not get validated
Car car = new Car( "VW""USD-123"4 );
car.setPassedVehicleInspection( true );
Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );
assertEquals( 0, constraintViolations.size() );
// create a driver who has not passed the driving test
Driver john = new Driver( "John Doe" );
john.setAge( 18 );
// now let's add a driver to the car
car.setDriver( john );
constraintViolations = validator.validate( car );
assertEquals( 1, constraintViolations.size() );
assertEquals(
        "The driver constraint should also be validated as part of the default group",
        constraintViolations.iterator().next().getMessage(),
        "You first have to pass the driving test"
);
```ss the driving test"
);

本文由 mdnice 多平台发布

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/55023.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于寄生捕食算法优化的BP神经网络(预测应用) - 附代码

基于寄生捕食算法优化的BP神经网络&#xff08;预测应用&#xff09; - 附代码 文章目录 基于寄生捕食算法优化的BP神经网络&#xff08;预测应用&#xff09; - 附代码1.数据介绍2.寄生捕食优化BP神经网络2.1 BP神经网络参数设置2.2 寄生捕食算法应用 4.测试结果&#xff1a;5…

服务器和普通电脑有何区别?43.248.189.x

简单来讲&#xff0c;服务器和电脑的功能是一样的&#xff0c;我们也可以把服务器称之为电脑&#xff08;PC机&#xff09;&#xff0c;只是服务器对稳定性与安全性以及处理器数据能力有更高要求&#xff0c;比如我们每天浏览一个网站&#xff0c;发现这个网站每天24小时都能访…

【ASP.NET】LIS实验室信息管理系统源码

LIS系统&#xff0c;即实验室信息管理系统&#xff0c;是一种基于互联网技术的医疗行业管理软件&#xff0c;它可以帮助实验室进行样本管理、检测流程管理、结果报告等一系列工作&#xff0c; 提高实验室工作效率和质量。 一、LIS系统的功能 1. 样本管理 LIS系统可以帮助实验…

【局部活动轮廓】使用水平集方法实现局部活动轮廓方法研究(Matlab代码实现)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…

SpringBoot项目(支付宝整合)——springboot整合支付宝沙箱支付 从极简实现到IOC改进

目录 引出git代码仓库准备工作支付宝沙箱api内网穿透 [natapp.cn](https://natapp.cn/#download) springboot整合—极简实现版1.导包配置文件2.controller层代码3.进行支付流程4.支付成功回调 依赖注入的改进1.整体结构2.pom.xml文件依赖3.配置文件4.配置类&#xff0c;依赖注入…

下载的文件被Windows 11 安全中心自动删除

今天从CSDN上下载了自己曾经上传的文件&#xff0c;但是浏览器下载完之后文件被Windows安全中心自动删除&#xff0c;说是带病毒。实际是没有病毒的&#xff0c;再说了即便有病毒也不应该直接删除啊&#xff0c;至少给用户一个保留或删除的选项。 研究了一番&#xff0c;可以暂…

机器视觉之平面物体检测

平面物体检测是计算机视觉中的一个重要任务&#xff0c;它通常涉及检测和识别在图像或视频中出现的平面物体&#xff0c;如纸张、标志、屏幕、牌子等。下面是一个使用C和OpenCV进行平面物体检测的简单示例&#xff0c;使用了图像中的矩形轮廓检测方法&#xff1a; #include &l…

设计模式之八:迭代器与组合模式

有许多方法可以把对象堆起来成为一个集合&#xff08;Collection&#xff09;&#xff0c;比如放入数组、堆栈或散列表中。若用户直接从这些数据结构中取出对象&#xff0c;则需要知道具体是存在什么数据结构中&#xff08;如栈就用peek&#xff0c;数组[]&#xff09;。迭代器…

推荐前 6 名 JavaScript 和 HTML5 游戏引擎

推荐&#xff1a;使用 NSDT场景编辑器 助你快速搭建3D应用场景 事实是&#xff0c;自从引入JavaScript WebGL API以来&#xff0c;现代浏览器具有直观的功能&#xff0c;使它们能够渲染更复杂和复杂的2D和3D图形&#xff0c;而无需依赖第三方插件。 你可以用纯粹的JavaScript开…

tensordataset 和dataloader取值

测试1 from torch.utils.data import TensorDataset,DataLoader import numpy as np import torch a np.array([[1,2,3],[2,3,3],[1,1,2],[10,10,10],[100,200,200],[-1,-2,-3]]) print(a)X torch.FloatTensor(a) print(X)dataset TensorDataset(X,X)测试2 from torch.uti…

字节一面:闭包是什么?闭包的用途是什么?

前言 最近博主在字节面试中遇到这样一个面试题&#xff0c;这个问题也是前端面试的高频问题&#xff0c;因为在前端开发的日常开发中我们经常会用到闭包&#xff0c;我们会借助闭包来封装一些工具函数&#xff0c;所以更深的了解闭包是很有必要的&#xff0c;博主在这给大家细细…

自动驾驶感知传感器标定安装说明

1. 概述 本标定程序为整合现开发的高速车所有标定模块,可实现相机内参标定和激光、相机、前向毫米波 至车辆后轴中心标定,标定参数串联传递并提供可视化工具验证各个模块标定精度。整体标定流程如下,标定顺序为下图前标0-->1-->2-->3,相同编号标定顺序没有强制要求…

Python学习笔记:正则表达式、逻辑运算符、lamda、二叉树遍历规则、类的判断

1.正则表达式如何写&#xff1f; 序号实例说明1.匹配任何字符(除换行符以外)2\d等效于[0-9]&#xff0c;匹配数字3\D等效于[^0-9]&#xff0c;匹配非数字4\s等效于[\t\r\n\f]&#xff0c;匹配空格字符5\S等效于[^\t\r\n\f]&#xff0c;匹配非空格字符6\w等效于[A-Za-z0-9]&…

<JDBC>

文章目录 1.JDBC核心技术1.数据的持久化2.JAVA中的数据存储技术3.JDBC介绍4.JDBC体系结构5.JDBC程序编写步骤 2.获取数据库连接1.Driver接口实现类2.注册与加载JDBC驱动3.URL4.用户和密码 3. PreparedStatement 和 Statement1.PreparedStatement介绍2. PreparedStatement vs St…

CMake3.27+OpenCV4.8+VS2019+CUDA配置

1、准备工作 CMake3.27OpenCV4.8opencv_contrib-4.8.0CUDACUDNNTensorRT下载好并安装cuda 2、正式开始安装 启动CMake开始配置 打开刚解压的cmake文件夹中找到bin目录下的cmake-gui.exe 点击cmake中左下角的 Configure进行第一次配置&#xff0c;会弹出选择环境对话框 再点击Fi…

HodlSoftware-免费在线PDF工具箱 加解密PDF 集成隐私保护功能

HodlSoftware是什么 HodlSoftware是一款免费在线PDF工具箱&#xff0c;集合编辑 PDF 的简单功能&#xff0c;可以对PDF进行加解密、优化压缩PDF、PDF 合并、PDF旋转、PDF页面移除和分割PDF等操作&#xff0c;而且工具集成隐私保护功能&#xff0c;文件只在浏览器本地完成&…

windows系统依赖环境一键安装

window系统程序依赖库&#xff0c;可以联系我获取15958139685 脚本代码如下&#xff0c;写到1. bat文件中&#xff0c;双击直接运行&#xff0c;等待安装完成即可 Scku.exe -AVC.exe /SILENT /COMPONENTS"icons,ext\reg\shellhere,assoc,assoc_sh" /dir%1\VC

Wireshark流量分析

目录 1.基本介绍 2.基本使用 1&#xff09;数据包筛选: 2&#xff09;筛选ip&#xff1a; 3&#xff09;数据包还原 4&#xff09;数据提取 3.wireshark实例 1.基本介绍 在CTF比赛中&#xff0c;对于流量包的分析取证是一种十分重要的题型。通常这类题目都是会提供一个包含…

PHP之 导入excel表格时,获取日期时间变成浮点数

读取到的时间 float(0.20833333333333) 原格式 15:00:00 代码 if (Request::isPost()) {$file_url input(upfile); // 本地上传文件地址// 读取文件内容$local_file_url __dir__./../../../public.$file_url;// $spreadsheet new Spreadsheet();// $sheet $spreadsheet-…

SQL中ON筛选和Where筛选的区别

转载&#xff1a;sql连接查询中on筛选与where筛选的区别https://zhuanlan.zhihu.com/p/26420938 结论:on后面接上连接条件&#xff0c;where后面接上过滤条件