在给pojo 进行数据校验的时候, 比如id 在新增的时候必须不能为空, 跟新的时候必须不能为空,这个时候就可以对这个属性进行group 的分组
首先定义两个空的接口
public interface Insert{} //新增的校验接口
public interface update{}//更新的校验接口
不用写任何的实现.只需要空接口就可以了,然后在controller中 指定使用哪一个校验规则: 具体代码例子如下:
pojo:
@Data
@ToString
public class Book implements Serializable {
private static final long serialVersionUID = 1670292046158771865L;
@NotNull(groups = {Update.class} , message = "主键必须不为空")
@Null(groups = {Insert.class},message = "主键必须为空")
private Integer id;
private String name;
}
普通的请求映射
@RequestMapping("/book/insert")
@ResponseBody
public String insert(@Validated({Insert.class}) Book book) {
log.info("这是新增");
System.out.println(book);
/* if(true){
throw new Exception("故意错误");
}*/
return "新增";
}
@RequestMapping("/book/update")
@ResponseBody
public String update(@Validated(Update.class) Book book) {
System.out.println(book);
log.info("这是更新");
return "更新";
}
两个标志性接口 什么也不用写
public interface Insert {
}
public interface Update {
}
写一个这样的类 然后返回相应的格式 这里的jsonresult 是我自己封装的 统一给前台 的数据
如果只是一种的话,可以直接使用@valid 进行校验