Last active
December 19, 2015 21:08
-
-
Save barorion/6017731 to your computer and use it in GitHub Desktop.
Invoking Hibernate's schema validaton using a dedicated Spring bean
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
| package com.ravello.management.server.data; | |
| import javax.inject.Inject; | |
| import org.hibernate.cfg.Configuration; | |
| import org.hibernate.tool.hbm2ddl.SchemaValidator; | |
| import org.springframework.context.ApplicationContext; | |
| import org.springframework.orm.hibernate4.LocalSessionFactoryBean; | |
| import org.slf4j.Logger; | |
| import org.slf4j.LoggerFactory; | |
| public class SchemaValidator { | |
| @Inject | |
| private ApplicationContext applicationContext; | |
| private Configuration configuration; | |
| private final Logger log = LoggerFactory.getLogger(SchemaValidator.class); | |
| // a workaround bean to validate schema, since setting hbm2ddl.auto=validate causes the sessionFactory bean to be | |
| // loaded before the Flyway bean | |
| public void validate() { | |
| try { | |
| LocalSessionFactoryBean localSessionFactoryBean = (LocalSessionFactoryBean) applicationContext | |
| .getBean("&sessionFactory"); // gets the original instance, not the bean; assuming your session factory bean is 'sessionFactory' | |
| configuration = localSessionFactoryBean.getConfiguration(); | |
| SchemaValidator hibernateSchemaValidator = new SchemaValidator(configuration); | |
| hibernateSchemaValidator.validate(); | |
| log.info("successfully validated schema"); | |
| } | |
| catch (Exception e) { | |
| throw new RuntimeException("Error while validating db schema; fix db and restart application", e); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment