Running SpringLiquibase before hibernation

I use SpringLiquibase to automatically apply my Liquibase update during application startup. In general, this works fine, but when I install hibernate.hbm2ddl.auto for “checking,” then hibernation starts complaining about the database schema before the campaign seems to be able to apply the updates. My configuration looks like this:

@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = "com.myapp")
@PropertySource(value = {"classpath:myapp.properties"})
@EnableJpaRepositories("com.myapp")
public class MyappConfig {

    @Resource
    private Environment env;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(env.getRequiredProperty("jdbc.driver"));
        dataSource.setUrl(env.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(env.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(env.getRequiredProperty("jdbc.password"));

        return dataSource;
    }

    @Bean
    public SpringLiquibase liquibase() {
        SpringLiquibase liquibase = new SpringLiquibase();
        liquibase.setDataSource(dataSource());
        liquibase.setChangeLog("classpath:liquibase/liquibase-master-changelog.xml");
        return liquibase;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        entityManagerFactoryBean.setPackagesToScan("com.myapp");

        entityManagerFactoryBean.setJpaProperties(hibernateProperties());

        return entityManagerFactoryBean;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();

        String[] propertyNames = new String[]{"hibernate.dialect", "hibernate.show_sql", "hibernate.hbm2ddl.auto"};

        for (String propertyName : propertyNames) {
            properties.put(propertyName, env.getRequiredProperty(propertyName));
        }
        return properties;
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return transactionManager;
    }

}

Is there a way to get Liquibase to apply its updates before hibernate tries to validate the schema?

+4
source share
1 answer

Thanks to M. Deinum, I was able to solve this using

@Bean
@DependsOn("liquibase")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
   [...]
}

@DependsOn , Hibernates.

+3

Source: https://habr.com/ru/post/1569209/


All Articles