5 min read.

This blog is regarding the multiple connection with a single Spring Boot Application. This blog is written for the Spring Developers with moderate experience.

We are going to use MySQL database for this demo, any other database can also be configured we just have to change its driver name in configurations.

Lets start with configuration in application.properties

In above code snippet, we can observe that for different database we have got different configuration. Use your database name instead of db1 and similarly for database 2, provide the name.

Now let’s configure the datasource for our different database. Notice that for each database configuration we will have a separate Spring Config File. Let’s configure the  datasource 1 first :

“com.pramati.repository.db1” contains the repository layer aka DAO layer for database 1, db1.

“com.pramati.model.db1” contains the model or entities  for database 1, db1.

Similarly we will configure the datasource for database 2, db2 :

“com.pramati.repository.db2” contains the repository layer aka DAO layer for database 1, db1.

“com.pramati.model.db2” contains the model or entities  for database 1, db1.

As noticed we have configured the Datasources, Entity Manager and Transaction Manager  for db1 and db2. in

Now we will use these configured datasources in our application. We can just autowire the Dao class and it is ready to use anywhere in our application.

For the transactions we have to explicitly set the transaction manager for each database we can directly annotate our transaction methods, see sample below :

That’s it folks. Stay tuned for more blogs.

Please visit below link to check out the working code :

https://github.com/atshvrma/SpringBoot_MultipleDatasources.git