解决不同请求需要的同一实体类参数不同(分组校验validation)

问题概述

新增目录是自动生成id,不需要id参数;更新目录需要id,不能为空

pom.xml中已有spring-boot-starter-validation依赖

java 复制代码
 <!--validation(完成属性限制,参数校验)-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>

实体类category

java 复制代码
package com.yjzx.pojo;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;

import java.time.LocalDateTime;

@Data
public class Category {
    @NotNull
    private Integer cid;
    @NotEmpty
    private String categoryName;
    @NotEmpty
    private String categoryAlias;//别名
    private Integer createUser;//用户ID
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updateTime;

    
}

新增目录Controller代码

java 复制代码
 @PostMapping
    public Result add(@RequestBody @Validated Category category){
        categoryService.add(category);
        return Result.success();
    }

更新目录Controller代码

java 复制代码
 @PutMapping
    public Result update(@RequestBody @Validated Category category){
        categoryService.update(category);
        return Result.success();
    }

解决方法

通过validation分组校验

在category实体类中加入不同接口

java 复制代码
 //如果校验项未指定分组,默认Default分组
    //分组之间可以继承,A extends B,那么A中有B的校验项
    public interface Add extends Default {

    }
    public interface Update extends Default{

    }

在区别属性前加入类似

java 复制代码
 @NotNull(groups = Update.class)
    private Integer cid;

最后在Controller的校验中指定interface

java 复制代码
 @PostMapping
    public Result add(@RequestBody @Validated(Category.Add.class) Category category){
        categoryService.add(category);
        return Result.success();
    }
java 复制代码
 @PutMapping
    public Result update(@RequestBody @Validated(Category.Update.class) Category category){
        categoryService.update(category);
        return Result.success();
    }

即可完成分组校验

注:学习视频总结,如有不足,欢迎补充

相关推荐
饮水桶_T3 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
她的男孩3 小时前
Spring Boot 接 Flowable:请假单要同时走财务和行政,包容分支和默认分支怎么配
java·spring boot·工作流引擎
炸膛坦客3 小时前
单片机/C/C++八股:(三十四)C 语言函数参数入栈顺序
c语言·开发语言·c++
咖啡八杯4 小时前
LoginUser 适配器模式:适配 SysUser 到 UserDetails
java·开发语言·后端·框架·适配器模式·若依
bufengwangluo5 小时前
企业上网行为管理:代理网关部署位置怎么选,策略怎么落
开发语言·php
北冥有鱼5 小时前
从 bean::method 里抠出注解:Java 方法引用元数据反查全记录
java·后端
CoderYanger5 小时前
Java EE 进阶:11. SpringBoot 统一功能处理(第四弹):@ControllerAdvice 源码分析+案例代码
java·数据库·spring boot·后端·spring·java-ee·mybatis
饮水桶_T6 小时前
HashMap笔记
开发语言·数据结构·笔记
布莱克6057 小时前
Swift 下标(Subscript)详解:从语法到实战
服务器·开发语言·ios·ssh·swift·下标
鲸渔8 小时前
【AI Agent系列课程23-Python 基础23】测试入门:为函数写第一个 pytest 用例
开发语言·python·pytest·ai编程