解决javax.validation.ConstraintViolationException

错误信息

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";
    }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值