Dynamically change data source connection at runtime in Spring Boot

12.4k views Asked by At

I have a spring-boot application with one database. Now I would like to integrate the possibility to copy some data from this database to another database. The connection to the second database should be done during runtime. I insert in my frontend the second database connection and start the copy from the first database to the second. The two databases have the same tables and I would like to use the same repositories. Is it possible to do that? If yes, do you know some code example or documentation? I'm trying to find the correct approach to do that.

Thank you!

3

There are 3 answers

0
Mah On BEST ANSWER

Alternative solution could be to use AbstractRoutingDatasource: https://www.baeldung.com/spring-abstract-routing-data-source

1
gsan On

This answer explains how to configure two data sources for a single Spring Boot application.

Also this tutorial explains the same concept with a detailed example.

The copying procedure could be done by fetching all the objects from each table on the main db, deleting id values and saving them to the second db.

0
SoftWar On

I would like to write code for others on the same search:

_context.Database.CloseConnection();
_context.Database.SetConnectionString("NewConnectionString");
_context.Database.OpenConnection();

this will connect you whatever DB you want to connect...