简体   繁体   English

在 Spring Boot 中使用两个数据库连接

[英]working with two db connections in spring boot

I want to work with two databases in Spring Boot, - some models go to db1, others to db2我想在 Spring Boot 中使用两个数据库,-一些模型转到 db1,其他模型转到 db2

But how can i swap between them, or tell which repo belongs to which db?但是我如何在它们之间交换,或者告诉哪个 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

You are using the same property to define two distinguished datasources, which is incorrect.您使用相同的属性来定义两个不同的数据源,这是不正确的。 You have to define your two datasources properties for example :您必须定义两个数据源属性,例如:

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

And then in your Spring configuration define the datasources.然后在您的 Spring 配置中定义数据源。 For example :例如 :

@Bean
@Primary
@ConfigurationProperties(prefix = "spring.postgresql.datasource")
public DataSource postgresqlDataSource() {
    return DataSourceBuilder
                .create()
                .build();
}

And

@Bean
@Primary
@ConfigurationProperties(prefix = "spring.mysql.datasource")
public DataSource mysqlDataSource() {
    return DataSourceBuilder
                .create()
                .build();
}

Followthis tutorial to have further information.按照本教程获取更多信息。

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

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