【问题标题】:Spring Boot with multiple database using hibernate and JpaRepository使用 hibernate 和 JpaRepository 具有多个数据库的 Spring Boot
【发布时间】:2015-11-18 21:35:57
【问题描述】:

如何在Spring Boot中实现多数据库配置??? 如何使用hibernate创建具有2个不同数据库的spring Boot MVC应用程序???

application.properties(DB1=core,DB2=staging)

server.port=8772


spring.core.driverClassName=com.mysql.jdbc.Driver
spring.core.url=jdbc:mysql://ip:port/coredb
spring.core.username=uname
spring.core.password=pwd


spring.staging.driverClassName=com.mysql.jdbc.Driver
spring.staging.url=jdbc:mysql://ip:port/stagingdb
spring.staging.username=uname
spring.staging.password=pwd

存储库:

public interface IStagingEntityDao  extends   
JpaRepository<StagingEmployee, Integer>{ 

      Query("select e from StagingEmployee e")
      public List<StagingEmployee> getEntityData();

}

数据库配置:

public class DBConfig {

    @Bean(name="stagingDataSource")
    @Primary
    @ConfigurationProperties(prefix="spring.staging")
    public DataSource stagingDataSource()
    {
        return DataSourceBuilder.create().build();
    }

    @Bean(name="coreDataSource")
    @ConfigurationProperties(prefix="spring.core")
    public DataSource coreDataSource()
    {
        return DataSourceBuilder.create().build();
    }
}

要求:

我只想将数据从一个数据库复制到另一个数据库 将员工视为实体我想将数据从 db1 复制到 db2 到目前为止我所做的是我创建了控制器(@RestController)和服务和存储库,它们从 db 1 获取数据并通过在单个 spring boot 应用程序本身中调用相应的服务将其推送到 db2。

例外: 无法确定数据库类型 NONE 的嵌入式数据库驱动程序类。如果您想要一个嵌入式数据库,请在类路径中放置一个受支持的数据库。

以上配置中缺少什么????

【问题讨论】:

    标签: hibernate spring-boot spring-data-jpa


    【解决方案1】:

    我认为你会发现它很有用

    http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-two-datasources

    它展示了如何定义多个数据源并将其中一个分配为主数据源。

    这是一个相当完整的示例,还包含分发事务 - 如果您需要的话。

    http://fabiomaffioletti.me/blog/2014/04/15/distributed-transactions-multiple-databases-spring-boot-spring-data-jpa-atomikos/

    您需要创建 2 个配置类,分离模型/存储库包等以简化配置。

    此外,在上面的示例中,它手动创建数据源。您可以使用 spring doc 上的方法和 @ConfigurationProperties 注释来避免这种情况。这是一个例子:

    http://xantorohara.blogspot.com.tr/2013/11/spring-boot-jdbc-with-multiple.html

    希望对你有帮助

    【讨论】:

    • 我尝试使用两个不同的数据源作为主要和次要数据源,但它不起作用。它给出“无法确定数据库类型 NONE 的嵌入式数据库驱动程序类。如果您想要一个嵌入式数据库,请在类路径。”
    • 你可以将 spring.xx.url 更改为 spring.xx.jdbcUrl 并尝试 agin 吗?
    • Gokhan Oner 试过但结果相同。我想我错过了更多配置。关于数据库访问,我只有以上 3 个配置 ir app.properties、扩展 Jparepository 的 Respository 接口和创建 2 个数据源的 DBConfig.java,如上所示,没有其他用于数据库访问的配置。
    • 你能把你的项目放到github上或者分享一下吗??
    • 由于某种原因,我无法分享项目。但我可以向您解释。我到底需要实现什么,我在我的问题参考编辑中简要解释。
    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 2015-12-26
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    相关资源
    最近更新 更多