Spring Boot 2 with Multiple DataSources

Jay Ehsaniara
3 min readDec 31, 2019

--

In this page I’m going to explain, How your spring boot application can interact with multiple data-sources not necessarily same type (Postgres for this demo) But it can be applicable across the other relational databases. There are cases that you need to have multiple datasources from different vendors, but the general concept is similar, and this example can be useful with little bit of changes in the project configuration (application.yml)

For this demo I choose PostgresSql Data Replication case, which is common in high load database with high traffic in Application.

There are times that even having the best DataBase (PostgresSql, Oracle, MySql, .. ) Tuning can not be as help-full as much as When you separate Read DB and Writes DB in Application Level.

Postgres Setup

For This Demo you need 2 separate Postgres DataBase where one as Master and the other re one as a Replica.

For this demo I have used two PostgresSql which is running in my local docker on 2 separated port as 5432 and 5433

you can simply run the following 2 docker-compose files as:

Write PostgresSql on port 5432 — Docker-Compose
Read PostgresSql on port 5433 — Docker-Compose

Spring Boot Setup

From https://start.spring.io/ select web, data-jpa, lombok, postgresDriver

Or Select the following share link:

select web, data-jpa, lombok, postgresDriver

Once you Generate and download the zip file, you should have similar POM file as:

for this demo I use HikariDataSource as a default connection pool library by Spring Boot 2.2.2

we need to have 2 separate DataSource and EntityManager one for the Writes(Master/Primary) and one for Reads(Slave/Secondary).

on application.yml, datasource-write is the Master(Primary) and datasource-read is the Slave (Secondary)

Since both DataSourceConfigWrite and DataSourceConfigRead are taking their configs from: “spring.datasource-write” and “spring.datasource-read”, the entityManagerFactory for each datasource can not get JPA configurations from application.yml . Thats why JPA configuration are added later on from static Property “JPA_PROPERTIES” . you can also add independent @ConfigurationProperties(“spring.jpa”) to supply your JPA configs based on your spring profile.

As you see I have 2 data-source as: datasource-write and datasource-read with their own credentials.

DataSource Configurations for WriteDB:

DataSourceConfigWrite.java

DataSource Configurations for ReadDB:

DataSourceConfigRead.java

Read and Write repositories should be in a separated packages :

Write package: “com.ehsaniara.multidatasource.repository.writeRepository”
Read Package: “com.ehsaniara.multidatasource.repository.readRepository”

You also need to set:

and the actual logics are in the service layer:

When you run the application you can see 2 Persistence Unit as Read and Write

I have add the project SourceCode in GitHub

--

--

Responses (2)