Last active
December 27, 2021 20:33
-
-
Save rponte/e6530d90e38a625874bf174d24abaaa0 to your computer and use it in GitHub Desktop.
Spring Boot: integrating Bean Validation between Spring and Hibernate (supporting DI on custom validations with Hibernate)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Configuration | |
public class BeanValidationConfig { | |
/** | |
* The idea here is to configure Hibernate to use the same ValidatorFactory used by Spring, | |
* so that Hibernate will be able to handle custom validations that need to use dependency injection (DI) | |
*/ | |
@Bean | |
public HibernatePropertiesCustomizer hibernatePropertiesCustomizer(final Validator validator) { | |
return new HibernatePropertiesCustomizer() { | |
@Override | |
public void customize(Map<String, Object> hibernateProperties) { | |
hibernateProperties.put("javax.persistence.validation.factory", validator); | |
} | |
}; // or replace with lambda: return hibernateProperties -> hibernateProperties.put("javax.persistence.validation.factory", validator); | |
} | |
} |
It's important to notice that your custom validation may be executed on persist and merge/update operations inside the same transaction, what may be too expensive in some cases (depending on the logic inside your validator):
@Transactional
public void create(Product product) {
entityManager.persist(product); // validation will be executed here
// ... some business logic
product.setNsu(nsuGenerator.generate());
entityManager.merge(product); // validation will be executed here again
}
If you want to execute your custom validation (or any validation) only on persist, you can use Validation Groups as discussed on this thread in Stack Overflow.
Here is a very good explanation about why Bean Validation with Hibernate does not support dependency injection (DI) by default: Video Dev Eficiente: Como funciona a integração entre o Spring e a Bean Validation
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Some interesting links: