Spring Boot 2 with Multiple DataSources

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:

Spring Boot Setup

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

Or Select the following share link:

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).

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:

DataSource Configurations for ReadDB:

Read and Write repositories should be in a separated packages :

You also need to set:

and the actual logics are in the service layer:

I have add the project SourceCode in GitHub

Software Engineer