Spring Boot Multiple Database Configuration

Sometimes it’s our application requirement to deal with multiple databases. Spring Boot helps us to configure multiple databases in a single application. This blog will help to configure multiple datasources into a spring boot application.

To use multiple DataSources, let’s add the following details in the property file.

Here we configured ‘foo’ datasource and ‘bar’ datasource.


JPA Entities and JPA Repositories

 Let’s define the following 2 JPA entities and repositories.

Product Entity

User Entity

Product Repository 

User Repository 

We added both entities and repositories in different packages.

Package Structure

We will have a different package structure for both database entities and repositories. This is important while creating configuration classes. While creating config classes, we need to specify the base packages which will be used by Spring to read different configurations and create multiple Datasource. For our example, this is how the package structure looks like:

DataSource Configuration

We will create two Spring configuration classes whose responsibilities are to read the configurations and make sure all necessary setup/classes are available to our project on the application startup.

FooDatabase Configuration 

In the above example class:

@Configuration: indicate that our class declares @Bean methods that will be processed by the Spring container to be used at runtime.

@EnableTransactionManagement: used to allow the usage of annotation-driven transaction management capability.

@EnableJpaRepositories: since we are using spring data JPA, this annotation is required to tell Spring to enable JPA repositories. We specified the entity manager factory and the transaction manager beans to be used in the JPA repositories.

@ConfigurationProperties: This annotation tells spring to pick up the data source properties that are prefixed with “spring.foo.datasource” from the application.properties file and build a data source using DataSourceBuilder.

@Primary: Basically tell the spring that the configured data source is primary.

BarDatabase Configuration 

When we are dealing with just one datasource and Spring Boot, data source configuration is simple. Spring Boot provides a lot of autoconfiguration.

However, if you need to connect to multiple data sources with Spring Boot, additional configuration is needed.

Leave a Reply