Spring JPA does not check bean for update

I am using Spring Boot 1.5.7, Spring JPA, Hibernate validation, Spring Data REST, Spring HATEOAS.

I have a simple bean as follows:

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

    @NotBlank
    private String name;
}

As you can see, I am using @NotBlank. According to the Hibernate documentation, validation should be done on a preliminary and preliminary 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 is correct. Instead, in this case, the check does not 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 is no answer. Why is validation not performed by the update () method? Advice for solving the problem?

+4
source share
2 answers

, ConstraintViolationException , Hibernate . () saveAndFlush().

+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
}

TransactionTemplate Spring.

0

Source: https://habr.com/ru/post/1687885/


All Articles