是否有可能在Spring Boot中运行两个使用spring.jpa.generate-ddl填充的嵌入式数据库?

时间:2017-02-23 01:26:38

标签: spring-boot h2 spring-orm

我在应用程序中连接了两个数据库。

我想设置一个dev-only配置文件,使用嵌入式H2数据库来模拟这些数据库,我希望使用spring.jpa.generate-ddl=true自动创建它们的模式。每个数据库的实体类都在不同的java包中,我希望在这里可以帮助我。

是否有可能使用spring的autoconf机制?

1 个答案:

答案 0 :(得分:1)

可以在spring boot中使用多个数据库。 但是spring boot只能自动配置一个数据库。 您需要自己配置第二个数据库。

@Bean
@ConfigurationProperties(prefix="second.datasource")
public DataSource secondDataSource(){
  return DataSourceBuilder
        .create()
        .driverClassName("org.h2.Driver")
        .build();

}

如果您只需要一个jdbc连接,这已经足够了。如果您想使用JPA,还需要第二个JPA配置,它使用第二个数据源。

@Bean(name="secondEntityManager")
public LocalContainerEntityManagerFactoryBean mySqlEntityManagerFactory(EntityManagerFactoryBuilder builder,DataSource secondDataSource){
    return builder.dataSource(secondDataSource)                
        .packages("com.second.entity")
        .build();

}

您可以找到上面的代码以及更多in this post