【问题标题】:Spring JPA doesn't validate bean on updateSpring JPA 不会在更新时验证 bean
【发布时间】:2017-10-20 14:04:14
【问题描述】:

我正在使用 Spring Boot 1.5.7、Spring JPA、Hibernate 验证、Spring Data REST、Spring HATEOAS。

我有一个像这样的简单 bean:

@Entity
public class Person {
    @Id
    @GeneratedValue
    private Long id;

    @NotBlank
    private String name;
}

如您所见,我正在使用@NotBlank。根据 Hibernate 文档,应在 pre-persist 和 pre-update 时进行验证。

我创建了一个junit测试:

@Test(expected = ConstraintViolationException.class)
public void saveWithEmptyNameThrowsException() {  
    Person person = new Person();
    person.setName("");
    personRepository.save(person);
}

此测试运行良好,因此验证过程正确进行。相反,在这个测试用例中,验证不起作用:

@Test(expected = ConstraintViolationException.class)
public void saveWithEmptyNameThrowsException() {
   Person person = new Person();
   person.setName("Name");
   personRepository.save(person);

   person.setName("");
   personRepository.save(person);
}

我找到了另一个similar question,但很遗憾没有任何回复。 为什么不对 update() 方法进行验证?解决问题的建议?

【问题讨论】:

    标签: java spring hibernate spring-boot spring-validator


    【解决方案1】:

    我认为 ConstraintViolationException 没有发生,因为在更新期间 Hibernate 不会将结果当场刷新到数据库中。尝试用 saveAndFlush() 替换您的测试 save()。

    【讨论】:

      【解决方案2】:

      你在使用 Spring Boot JPA 测试吗?如果是,saveWithEmptyNameThrowsException 被包装在事务中,并且在方法执行完成之前不会提交。换句话说,该方法被视为一个工作单元。调用personRepository.save(除非您启用自动提交/刷新更改)不会诉诸您的实体更改的反映,但直到事务提交。这是您的测试的解决方法:

      @Test(expected = ConstraintViolationException.class)
      public void saveWithEmptyNameThrowsException() {
         // Wrap the following into another transaction
         // begin
            Person person = new Person();
            person.setName("Name");
            personRepository.save(person);
         // commit
      
         // Wrap the following into another transaction
         // begin
            person = ... get from persistence context
            person.setName("");
            personRepository.save(person);
         // commit
      }
      

      您可以在 Spring 中使用TransactionTemplate 进行程序化事务划分。

      【讨论】:

        猜你喜欢
        • 2014-04-11
        • 2013-04-16
        • 1970-01-01
        • 2020-06-30
        • 2019-04-04
        • 1970-01-01
        • 2020-12-21
        • 1970-01-01
        • 2021-02-13
        相关资源
        最近更新 更多