简体   繁体   中英

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

But how can i swap between them, or tell which repo belongs to which 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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