我正在使用Spring Boot 1.5.7,Spring JPA,Hibernate验证,Spring Data REST,Spring HATEOAS.
@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()方法上进行验证?建议解决问题?
最佳答案
我认为没有发生ConstraintViolationException,因为在更新期间Hibernate不会在现场将结果刷新到数据库.尝试使用saveAndFlush()替换测试save().
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。