Sometimes its our application requirement is to deal with multiple databases. Spring Boot helps us to configure multiple datasources with multiple databases in a single application. This page will give step by step instructions to configure multiple datasources into spring boot application.
We will go with Oracle and MySql databases in this example. Lets Start with the Heart of Spring boot Application pom.xml
Step 1: Adding Dependencies In pom.xml we will add 2 dependencies, one for Orcale and other for MySQL, If you are using another database, you can add the dependencies for those as well.
Note: Oracle dosen’t provide its jar file on any market place, you need to go to Oracle Official site and download the jar file for ojdbc7 then you need to refer that into your build path.
The configurations in application.properties file contains standard spring datasource configuration along with database type prefix (prefix is our custom one). The prefix helps us to identify the configuration. Here is the sample configurations:
Spring boot Configures its default data-source even if you don’t want, The @Springbootapplication annotation is responsible for creating all the default initial configuration. In case when you are defining your own data-source, you can disable the default one. You just need to add the following code in your main class, after@Springbootapplication
@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 entityManagerFactory and the transactionManager 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.oraclesql.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.
Step 5:MySQL Datasource Configuration
MySql DataSource Configurations are similar to Oracle DataSource Configurations. The differences are the prefix used in application.properties, and the packages where the entities and JPA repositories are located.
Step 6: How to Use You have done defining your datasources, now you should know how to use them. suppose you have a method getEmployeed() and you want to use oracle database in this method for any transaction operation then use it like this: