【发布时间】:2016-11-26 14:11:34
【问题描述】:
我想使用带有注释的 Spring Validation 来验证我的表单数据。 所以我有以下对象,例如:
@Entity
@ComponentScan
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
@NotEmpty
private String type;
...
}
正如您在此处看到的,我在type 字符串上使用了@NotEmpty。我只想用它来验证我的表单。它不应该验证数据库插入。
所以当我这样做时:
@RequestMapping(value = "/myForm", method = RequestMethod.POST)
public String categoryPOST(HttpServletRequest request, Model model, @Valid Category category, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "form";
}
return "redirect:/results";
}
它按我希望的方式工作。但是当我必须创建一个虚拟对象时:
Category category = new Category();
然后我对该空对象执行保存:
this.category_repository.save(category);
我得到了错误(只是其中的重要部分):
Caused by: javax.validation.ConstraintViolationException: Validation failed for classes [my.project.jpa.entity.Category] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='darf nicht leer sein', propertyPath=type, rootBeanClass=class my.project.jpa.entity.Category, messageTemplate='{org.hibernate.validator.constraints.NotEmpty.message}'}
]
这不是我想要的。我想使用注释进行表单验证,但我不希望对数据库操作执行验证。
这有可能吗?
其他信息
我使用以下方法得到了相同的结果:
javax.validation.constraints.NotNull;
注释。
【问题讨论】:
-
顺便说一句,实体上的
@ComponentScan注释看起来很奇怪。你确定你需要它吗? -
不,不确定。对春天完全陌生。
标签: hibernate spring-mvc bean-validation hibernate-validator