【问题标题】:working with two db connections in spring boot在 Spring Boot 中使用两个数据库连接
【发布时间】:2017-06-11 18:20:38
【问题描述】:
我想在 Spring Boot 中使用两个数据库,- 一些模型转到 db1,其他模型转到 db2
但是我怎样才能在它们之间进行交换,或者告诉哪个 repo 属于哪个 db?
# db1
spring.datasource.url=connectionString
spring.datasource.username=db1
spring.datasource.password=***
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
# db2
spring.datasource.url=connectionString
spring.datasource.username=db2
spring.datasource.password=***
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
【问题讨论】:
标签:
java
spring-boot
datasource
multiple-databases
【解决方案1】:
您使用相同的属性来定义两个可区分的数据源,这是不正确的。例如,您必须定义两个数据源属性:
spring.postgresql.datasource.url=jdbc:postgresql://localhost:5432/book_db
spring.postgresql.datasource.username=postgres
spring.postgresql.datasource.password=postgres
spring.postgresql.datasource.driver-class-name=org.postgresql.Driver
spring.mysql.datasource.url=jdbc:mysql://localhost:3306/author_db?autoReconnect=true&useSSL=false
spring.mysql.datasource.username=root
spring.mysql.datasource.password=
spring.mysql.datasource.driver-class-name=com.mysql.jdbc.Driver
然后在您的 Spring 配置中定义数据源。例如:
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.postgresql.datasource")
public DataSource postgresqlDataSource() {
return DataSourceBuilder
.create()
.build();
}
还有
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.mysql.datasource")
public DataSource mysqlDataSource() {
return DataSourceBuilder
.create()
.build();
}
关注this tutorial了解更多信息。