I'm using Spring Boot 1.5.7, Spring JPA, Hibernate validation, Spring Data REST, Spring HATEOAS.
I've a simple bean like this:
@Entity
public class Person {
@Id
@GeneratedValue
private Long id;
@NotBlank
private String name;
}
As you can see I'm using @NotBlank. According to Hibernate documentation the validation should be made on pre-persist and pre-update.
I created a junit test:
@Test(expected = ConstraintViolationException.class)
public void saveWithEmptyNameThrowsException() {
Person person = new Person();
person.setName("");
personRepository.save(person);
}
this test works fine and therefore the validation process happens correctly. Instead in this test case, the validation doesn't work:
@Test(expected = ConstraintViolationException.class)
public void saveWithEmptyNameThrowsException() {
Person person = new Person();
person.setName("Name");
personRepository.save(person);
person.setName("");
personRepository.save(person);
}
I found another similar question but unfortunately there isn't any reply. Why the validation is not made on update() method? Advice to solve the problem?
I think ConstraintViolationException is not occurred because during update Hibernate don't flush result to database on the spot. Try to replace in your test save() with saveAndFlush().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With