1、安装依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2、实体类
@TableName("user")
@Data
public class User {
//对应数据库的主键(uuid,自增id,雪花算法,redis,zookper)
@TableId(type = IdType.AUTO)
private Integer id;
@NotNull(message = "名称xxx不能为空")//空校验
@NotBlank //不能为空字符串
@Size(min = 1,max = 5,message = "ssssss")//字符串长度校验
private String name;
// @Min(value = 10,message = "最小值10")
// @Max(value = 90,message = "最大值为99")
@NotNull
// @Max(value = 50,message = "超过最大值")
// @Min(value = 10,message = "超过最小值")
@Range(min=10,max = 99,message = "错误")//数字范围校验
private Integer age;
@NotNull
private String email;
//逻辑删除字段
@TableLogic //逻辑删除注解
private Integer deleted;
//字段添加填充内容
//策略
// @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField(fill = FieldFill.INSERT)
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private LocalDateTime createTime;
//策略
// @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField(fill = FieldFill.INSERT)
private Integer createBy;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Integer updateBy;
@Version//乐观锁注解
private Integer version;
}
3、控制器,一定在需要验证的参数前加@Validated注解
@PostMapping("/insertUser")
public String insertUser(@Validated @RequestBody User user){
userMapper.insert(user);
return "OK";
}
4、常用注解
@Null 对象 被注解的元素必须为 null
@NotNull 对象 被注解的元素必须不为 null
@AssertTrue 布尔 被注解的元素必须为 true
@AssertFalse 布尔 被注解的元素必须为 false
@Min(value) 数字 被注解的元素必须为数字,其值必须大于等于最小值
@Max(value) 数字 被注解的元素必须为数字,其值必须小于等于最小值
@Size(max,min) 集合、数组、字符串 被注解的元素(集合、数组大小,字符串长度)必须在指定范围
@Past 日期 被注解的元素必须为过去的一个时间
@Future 日期 被注解的元素必须为未来的一个时间
@Pattern 对象 被注解的元素必须符合指定的正则表达式
@NotBlank 字符串 校验字符串去掉前后空格后长度不为0
@NotEmpty 字符串、集合、数组 校验对象不为空(字符串长度不为0,集合、数组大小不为0)
@Length 字符串 校验字符串长度在指定范围
@Range 数字、字符串 校验对象(字符串长度,数字大小)在指定范围
@Email 字符串 校验字符串为邮箱地址
@URL 字符串 校验字符串为URL地址
@CreditCardNumber 字符串 校验字符串为信用卡号
@ScriptAssert 对象 被注解的元素指定校验的方法,来进行复杂的校验,返回 true 或 false
5、参考
https://blog.csdn.net/qq_45594962/article/details/126719154