【问题标题】:Spring Form Validation validates database insert?Spring Form Validation 验证数据库插入?
【发布时间】: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;

注释。

【问题讨论】:

标签: hibernate spring-mvc bean-validation hibernate-validator


【解决方案1】:

是的,这是可能的。

第一个选项是为表单对象 (DTO) 和实体使用不同的类。

第二个选项是配置 Hibernate 并在保存前禁用验证。因为这个问题已经回答了好几次了,所以我将提供他们的链接:

【讨论】:

  • 好的,但是如果真的总是只想验证表单,而不是数据库操作,但我必须始终使用相同的对象怎么办?我现在正在进行的项目非常庞大,要在代码中找到我必须禁用验证的所有行将花费很长时间。那么有没有更好的方法来仅使用 spring 验证表单帖子?
  • 在休眠配置中,您不是为每个实体禁用验证,而是只禁用一次。或者,您有多个休眠配置?
猜你喜欢
  • 2012-05-05
  • 2014-10-08
  • 2013-11-21
  • 1970-01-01
  • 2014-04-14
  • 2016-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多