-1

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
Anders Pedersen
  • 2,255
  • 4
  • 25
  • 49
  • 1
    Possible duplicate of [Spring Boot Configure and Use Two DataSources](http://stackoverflow.com/questions/30337582/spring-boot-configure-and-use-two-datasources) – Patrick Jan 26 '17 at 09:58

1 Answers1

0

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();
}

Follow this tutorial to have further information.

benkuly
  • 1,144
  • 10
  • 28
Radouane ROUFID
  • 10,595
  • 9
  • 42
  • 80