【问题标题】:Is it possible to have two embedded databases running in Spring Boot that are populated using spring.jpa.generate-ddl?是否可以在 Spring Boot 中运行两个使用 spring.jpa.generate-ddl 填充的嵌入式数据库?
【发布时间】:2017-07-13 07:47:09
【问题描述】:

我在我的应用程序中有两个要连接的数据库。

我想设置一个仅限开发人员的配置文件,使用嵌入式 H2 数据库模拟这些数据库,并且我想使用 spring.jpa.generate-ddl=true 自动创建它们的架构。每个数据库的实体类都在不同的java包中,希望对我有帮助。

使用 spring 的 autoconf 机制可以做到这一点吗?

【问题讨论】:

    标签: spring-boot h2 spring-orm


    【解决方案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

    【讨论】:

    • 谢谢斯特凡。我已经设法靠自己做到了这一点。我的具体问题是尝试从我的实体类中填充这些嵌入式数据库。我知道我可以使用 schema.sql,但我想从实体中进行。
    猜你喜欢
    • 2017-07-11
    • 2022-08-18
    • 2022-06-24
    • 2013-10-11
    • 1970-01-01
    • 2021-12-27
    • 2019-09-01
    • 2018-06-13
    • 1970-01-01
    相关资源
    最近更新 更多