簡體   English   中英

Spring Boot-已配置兩個數據源-如何使用第二個數據源?

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

我已經在我的Spring Boot應用程序中從MySQL數據庫配置了兩個架構,並將一個數據源標記為Primary。

現在,我的問題是如何“使用”第二個數據源? 我正在使用基於JpaRepository的方法,當我嘗試將某些內容保存到位於第二個DB模式中的表中時,我的Spring Boot應用程序總是嘗試在第一個DB模式中找到該表,並最終拋出該表不存在的錯誤。

PS我已經在Entity類中正確標記了第二個數據庫模式。

以下是我的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

在此Blog上找到解決方案-ScatterCode

解決方法是,必須應用程序配置類分為兩類,並用以下所示注釋每個類:

配置類別1:

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

配置類別2:

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

一個dataSource應該位於第一個配置類中,而第二個則位於另一個類中。 同樣,將Entity類和JpaRepository接口移動到相應的包中,如上面的注釋所示。

干杯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM