Spring JPA不会在更新时验证bean

dre*_*nda 5 java spring hibernate spring-validator spring-boot

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

如你所见,我正在使用@NotBlank.根据Hibernate文档,验证应该在pre-persist和pre-update上进行.

我创建了一个junit测试:

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

此测试工作正常,因此验证过程正确.相反,在此测试用例中,验证不起作用:

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

   person.setName("");
   personRepository.save(person);
}
Run Code Online (Sandbox Code Playgroud)

我发现了另一个类似的问题,但遗憾的是没有任何答复.为什么不在update()方法上进行验证?建议解决问题?

Yur*_*hok 4

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