Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA doesn't validate bean on update

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?

like image 219
drenda Avatar asked Oct 20 '17 14:10

drenda


Video Answer


1 Answers

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().

like image 102
Yurii Kozachok Avatar answered Oct 16 '22 12:10

Yurii Kozachok