简体   繁体   English

Spring Boot-已配置两个数据源-如何使用第二个数据源?

[英]Spring Boot - two datasources configured - how to use second datasource?

I have configured two schemas from MySQL database in my Spring Boot application and have marked one datasource as Primary. 我已经在我的Spring Boot应用程序中从MySQL数据库配置了两个架构,并将一个数据源标记为Primary。

Now, my question is how can I "use" second datasource? 现在,我的问题是如何“使用”第二个数据源? I am using JpaRepository based approach and when I try to save something to a table which resides in second DB schema, my Spring boot application always try to find this table in first DB schema and eventually throws table does not exist error. 我正在使用基于JpaRepository的方法,当我尝试将某些内容保存到位于第二个DB模式中的表中时,我的Spring Boot应用程序总是尝试在第一个DB模式中找到该表,并最终抛出该表不存在的错误。

PS I have marked second DB schema in my Entity class correctly. PS我已经在Entity类中正确标记了第二个数据库模式。

Below is my application.properties file (prefix has been changed to omit confidential name): 以下是我的application.properties文件(前缀已更改为省略机密名称):

# source 1
myframework.data.sql.connections.dataSource.url=jdbc:mysql://localhost:3306/schema1?autoReconnect=true&useSSL=false&rewriteBatchedStatements=true
myframework.data.sql.connections.dataSource.user=root
myframework.data.sql.connections.dataSource.password=root
myframework.data.sql.connections.dataSource.driver-class-name=com.mysql.jdbc.Driver
myframework.data.sql.connections.dataSource.config.preferredTestQuery=select 1 from dual

# source 2
myframework.data.sql.connections.master.url=jdbc:mysql://localhost:3306/schema2?autoReconnect=true&useSSL=false&rewriteBatchedStatements=true
myframework.data.sql.connections.master.user=root
myframework.data.sql.connections.master.password=root
myframework.data.sql.connections.master.driver-class-name=com.mysql.jdbc.Driver

Found solution on this Blog - ScatterCode 在此Blog上找到解决方案-ScatterCode

The fix is that one has to split application configuration class into two and annotate each of the classes with what is shown below: 解决方法是,必须应用程序配置类分为两类,并用以下所示注释每个类:

Config class 1: 配置类别1:

@Configuration
@EnableTransactionManagement
@EnableConfigurationProperties({ MyServicefacadeProperties.class })
@EnableJpaRepositories(entityManagerFactoryRef = "myEntityManagerFactory", transactionManagerRef = "myTransactionManager", basePackages = {
    "com.myorg.foo" })

Config class 2: 配置类别2:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "masterEntityManagerFactory", transactionManagerRef = "masterTransactionManager", basePackages = {
            "com.myorg.foo.master" })

One dataSource should reside into first config class and second one in another. 一个dataSource应该位于第一个配置类中,而第二个则位于另一个类中。 Also, move the Entity class and JpaRepository interface into respective packages as indicated in annotations above. 同样,将Entity类和JpaRepository接口移动到相应的包中,如上面的注释所示。

Cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM