Multiple data source and schema creation in Spring Boot

spring.jpa.hibernate.ddl-auto=create has stopped working, not because you have two DataSources, but because your application’s creating its own LocalContainerEntityManagerFactoryBeans. This has the effect of disabling the auto-configuration of a LocalContainerEntityManagerFactoryBean so you now have to configure it yourself.

You can configure the two entity managers to have different schema generation behaviour like this (the first’s doing update, the second’s doing create):

@Bean(name = "externalEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean externalEntityManagerFactory(
        EntityManagerFactoryBuilder builder) {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("hibernate.hbm2ddl.auto", "update");
    return builder
            .dataSource(externalDataSource())
            .packages("cz.data.external.entity")
            .persistenceUnit(EXTERNAL)
            .properties(properties)
            .build();
}

@Bean(name = "internalEntityManagerFactory")
@Primary
public LocalContainerEntityManagerFactoryBean internalEntityManagerFactory(
        EntityManagerFactoryBuilder builder) {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("hibernate.hbm2ddl.auto", "create");
    return builder
            .dataSource(internalDataSource())
            .packages("cz.data.internal.entity")
            .persistenceUnit(INTERNAL)
            .properties(properties)
            .build();
}

Leave a Comment