Spring Boot 2 With Multiple Datasources
In this article, see how your Spring Boot application can interact with multiple datasources.
Join the DZone community and get the full member experience.
Join For Free
In this article, I’m going to explain how your Spring Boot application can interact with multiple datasources and not necessarily the same type (Postgres for this demo), but it can be applied 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 a few changes in the project configuration (application.yml).
For this demo, I chose PostgresSQL Data Replication, which is common in a high load database with high traffic in the 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 two separate Postgres databases where one is the master and the other one is the replica.
I have used two PostgresSQL databases, which are running on my local Docker on two separate ports: 5432 and 5433.
You might also want to read: Set up Multiple DataSources With Spring Boot and Spring Data in PCF
For simplicity, just run: docker-compose up --force-recreate
.
The docker-compose.yml
is already in the project, which contains two PostgresSQL databases in two different ports, with demo
database.
Note: You can always uninstall it as: docker-compose down
if you need to.
xxxxxxxxxx
version'3.1'
services
db1
image postgres
container_name postgres1
volumes
./postgres-data1:/var/lib/postgresql/data
ports
"5432:5432"
environment
POSTGRES_PASSWORD postgres_user_for_db_write
POSTGRES_USER postgres
POSTGRES_DB demo
db2
image postgres
container_name postgres2
volumes
./postgres-data2:/var/lib/postgresql/data
ports
"5433:5432"
environment
POSTGRES_PASSWORD postgres_user_for_db_read
POSTGRES_USER postgres
POSTGRES_DB demo
From https://start.spring.io/, select web, data-jpa, lombok, postgresDriver.
xxxxxxxxxx
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath></relativePath> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
pom.xml
For this demo, I used HikariDataSource as a default connection pool library by Spring Boot 2.2.2.
We need to have two separate datasources and EntityManagers, one for the writes (Master/Primary) and one for Reads (Slave/Secondary).
application.yml
xxxxxxxxxx
spring
datasource-write
driver-class-name org.postgresql.Driver
jdbc-url jdbc postgresql //localhost 5432/demo
username'postgres'
password'postgres_pass_for_db_write'
platform postgresql
hikari
idle-timeout10000
maximum-pool-size10
minimum-idle5
pool-name WriteHikariPool
datasource-read
driver-class-name org.postgresql.Driver
jdbc-url jdbc postgresql //localhost 5433/demo
username'postgres'
password'postgres_pass_for_db_read'
platform postgresql
hikari
idle-timeout10000
maximum-pool-size10
minimum-idle5
pool-name ReadHikariPool
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 configurations 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 can see, I have two datasources as datasource-write and datasource-read with their own credentials.
DataSource configurations for WriteDB:
xxxxxxxxxx
package com.ehsaniara.multidatasource.configurations;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import static com.ehsaniara.multidatasource.DemoApplication.JPA_PROPERTIES;
import static com.ehsaniara.multidatasource.DemoApplication.MODEL_PACKAGE;
/**
* @author Jay Ehsaniara, Dec 30 2019
*/
"spring.datasource-write") (
(
entityManagerFactoryRef = "entityManagerFactoryWrite",
transactionManagerRef = "transactionManagerWrite",
basePackages = {"com.ehsaniara.multidatasource.repository.writeRepository"}
)
public class DataSourceConfigWrite extends HikariConfig {
public final static String PERSISTENCE_UNIT_NAME = "write";
public HikariDataSource dataSourceWrite() {
return new HikariDataSource(this);
}
public LocalContainerEntityManagerFactoryBean entityManagerFactoryWrite(
final HikariDataSource dataSourceWrite) {
return new LocalContainerEntityManagerFactoryBean() {{
setDataSource(dataSourceWrite);
setPersistenceProviderClass(HibernatePersistenceProvider.class);
setPersistenceUnitName(PERSISTENCE_UNIT_NAME);
setPackagesToScan(MODEL_PACKAGE);
setJpaProperties(JPA_PROPERTIES);
}};
}
public PlatformTransactionManager transactionManagerWrite(EntityManagerFactory entityManagerFactoryWrite) {
return new JpaTransactionManager(entityManagerFactoryWrite);
}
}
DataSource Configurations for ReadDB:
xxxxxxxxxx
package com.ehsaniara.multidatasource.configurations;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import static com.ehsaniara.multidatasource.DemoApplication.JPA_PROPERTIES;
import static com.ehsaniara.multidatasource.DemoApplication.MODEL_PACKAGE;
/**
* @author Jay Ehsaniara, Dec 30 2019
*/
"spring.datasource-read") (
(
entityManagerFactoryRef = "entityManagerFactoryRead",
transactionManagerRef = "transactionManagerRead",
basePackages = {"com.ehsaniara.multidatasource.repository.readRepository"}
)
public class DataSourceConfigRead extends HikariConfig {
public final static String PERSISTENCE_UNIT_NAME = "read";
public HikariDataSource dataSourceRead() {
return new HikariDataSource(this);
}
public LocalContainerEntityManagerFactoryBean entityManagerFactoryRead(
final HikariDataSource dataSourceRead) {
return new LocalContainerEntityManagerFactoryBean() {{
setDataSource(dataSourceRead);
setPersistenceProviderClass(HibernatePersistenceProvider.class);
setPersistenceUnitName(PERSISTENCE_UNIT_NAME);
setPackagesToScan(MODEL_PACKAGE);
setJpaProperties(JPA_PROPERTIES);
}};
}
public PlatformTransactionManager transactionManagerRead(EntityManagerFactory entityManagerFactoryRead) {
return new JpaTransactionManager(entityManagerFactoryRead);
}
}
Read and Write repositories should be in a separated package:
xxxxxxxxxx
package com.ehsaniara.multidatasource.repository.writeRepository;
import com.ehsaniara.multidatasource.model.Customer;
import org.springframework.data.repository.CrudRepository;
/**
* @author Jay Ehsaniara, Dec 30 2019
*/
public interface CustomerWriteRepository extends CrudRepository<Customer, Long> {
}
xxxxxxxxxx
package com.ehsaniara.multidatasource.repository.readRepository;
import com.ehsaniara.multidatasource.model.Customer;
import org.springframework.data.repository.CrudRepository;
/**
* @author Jay Ehsaniara, Dec 30 2019
*/
public interface CustomerReadRepository extends CrudRepository<Customer, Long> {
}
You also need to set:
xxxxxxxxxx
package com.ehsaniara.multidatasource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.Properties;
public class DemoApplication {
public final static String MODEL_PACKAGE = "com.ehsaniara.multidatasource.model";
public final static Properties JPA_PROPERTIES = new Properties() {{
put("hibernate.dialect", "org.hibernate.dialect.PostgreSQL10Dialect");
put("hibernate.hbm2ddl.auto", "update");
put("hibernate.ddl-auto", "update");
put("show-sql", "true");
}};
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
And the actual logics are in the service layer:
xxxxxxxxxx
package com.ehsaniara.multidatasource.service;
import com.ehsaniara.multidatasource.model.Customer;
import com.ehsaniara.multidatasource.repository.readRepository.CustomerReadRepository;
import com.ehsaniara.multidatasource.repository.writeRepository.CustomerWriteRepository;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.util.Optional;
/**
* @author Jay Ehsaniara, Dec 30 2019
*/
public class CustomerServiceImpl implements CustomerService {
private final CustomerReadRepository customerReadRepository;
private final CustomerWriteRepository customerWriteRepository;
public CustomerServiceImpl(CustomerReadRepository customerReadRepository, CustomerWriteRepository customerWriteRepository) {
this.customerReadRepository = customerReadRepository;
this.customerWriteRepository = customerWriteRepository;
}
public Optional<Customer> getCustomer(Long id) {
return customerReadRepository.findById(id);
}
public Customer createCustomer(Customer customer) {
Assert.notNull(customer, "Invalid customer");
Assert.isNull(customer.getId(), "customer id should be null");
Assert.notNull(customer.getName(), "Invalid customer name");
return customerWriteRepository.save(customer);
}
public Customer updateCustomer(Customer customer) {
Assert.notNull(customer, "Invalid customer");
Assert.notNull(customer.getId(), "Invalid customer id");
return customerWriteRepository.save(customer);
}
}
I have added the project source code in GitHub.
Good luck!
Further Reading
Multiple Databases With Shared Entity Classes in Spring Boot and Java
Opinions expressed by DZone contributors are their own.
Comments