Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did Spring Data JPA save method didn't validate straight away?

I'm using Spring Boot (1.3.3.RELEASE) with Spring Data and Bean Validation on a project and I found an unexpected (at least to me) behaviour. I have an User entity and its UserRepository (an interface that extends JpaRepository). When I make a call like this:

userRepository.save(user);
logger.info("User saved with id", user.getId());

On a new and INvalid user, logger is called and shows that the user received an id. Even though nothing gets persisted and ConstraintViolationException is thrown at the end, after logging.

But if I change to:

userRepository.saveAndFlush(user);
logger.info("User saved with id", user.getId());

ConstraintViolationException is thrown right away and the logger line never gets reached.

This second behaviour, where the exception is thrown before the logger, is what I believe it would have to happen when I call userRepository.save() method.

What is wrong? Something about my project? Or my understanding on how bean validation is supposed to work?

like image 453
Bruno Krebs Avatar asked Sep 06 '25 19:09

Bruno Krebs


1 Answers

Depending on your flush strategy and Identity Generator the actual insert into DB may (and in your case it does) happen later. And in case of Hibernate it validates right before insert/update/delete (which in your case are postponed). See the sources of BeanValidationEventListener and its methods onPreInsert(), onPreUpdate() and onPreDelete().

like image 194
Stanislav Bashkyrtsev Avatar answered Sep 08 '25 12:09

Stanislav Bashkyrtsev