Skip to content

Instantly share code, notes, and snippets.

@rponte
Last active December 27, 2021 20:33
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save rponte/e6530d90e38a625874bf174d24abaaa0 to your computer and use it in GitHub Desktop.
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)
@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);
}
}
@rponte
Copy link
Author

rponte commented Feb 23, 2021

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.

@rponte
Copy link
Author

rponte commented Feb 23, 2021

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