错误信息
Caused by: javax.validation.ConstraintViolationException: Validation failed for classes [com.zxw.pojo.Type] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='分类名称不能为空', propertyPath=name, rootBeanClass=class com.zxw.pojo.Type, messageTemplate='分类名称不能为空'}
]
错误原因:
我是准备做一个非空校验的,所以在实体类中使用了@NotBlank,但我在测试时,提交空值时报错,并没有出现预想的校验信息,百度了一些文章,情况并不相同,直到看到http://blog.sina.com.cn/s/blog_7a5fe1f00101i356.html,给了我一点提示。我校验的是一个对象,需要在对象前使用@valid。
实体类:
@Data
@Entity
@Table(name = "t_type")
public class Type {
@Id
@GeneratedValue
private long id;
@NotBlank(message = "分类名称不能为空")
private String name;
@OneToMany(mappedBy = "type")
private List<Blog> blogs=new ArrayList<>();
}
控制层:
/**
* 新增分类
* @param type @valid代表要校验Type对象
* @param result
* @param attributes
* @return
*/
@PostMapping("/types")
public String post(@Valid Type type, BindingResult result, RedirectAttributes attributes){
if (result.hasErrors()){
return "admin/types-input";
}
Type t = this.typeService.saveType(type);
if (t==null){
attributes.addFlashAttribute("message","新增失败");
}else{
attributes.addFlashAttribute("message","新增成功");
}
return "redirect:/admin/types";
}