问题概述
新增目录是自动生成id,不需要id参数;更新目录需要id,不能为空
pom.xml中已有spring-boot-starter-validation依赖
<!--validation(完成属性限制,参数校验)--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency>
实体类category
package com.yjzx.pojo;import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;import java.time.LocalDateTime;@Data
public class Category {@NotNullprivate Integer cid;@NotEmptyprivate String categoryName;@NotEmptyprivate 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代码
@PostMappingpublic Result add(@RequestBody @Validated Category category){categoryService.add(category);return Result.success();}
更新目录Controller代码
@PutMappingpublic Result update(@RequestBody @Validated Category category){categoryService.update(category);return Result.success();}
解决方法
通过validation分组校验
在category实体类中加入不同接口
//如果校验项未指定分组,默认Default分组//分组之间可以继承,A extends B,那么A中有B的校验项public interface Add extends Default {}public interface Update extends Default{}
在区别属性前加入类似
@NotNull(groups = Update.class)private Integer cid;
最后在Controller的校验中指定interface
@PostMappingpublic Result add(@RequestBody @Validated(Category.Add.class) Category category){categoryService.add(category);return Result.success();}
@PutMappingpublic Result update(@RequestBody @Validated(Category.Update.class) Category category){categoryService.update(category);return Result.success();}
即可完成分组校验
注:学习视频总结,如有不足,欢迎补充