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