I want to create an application with Java, Spring and Spring JPA with multiple databases on run time.
Actually i am creating multi-tenant application with following flow:
1- one Application may be php: from website user will create account, the system will run the process and will create database and respective configuration.
2- Major application ( Java + Spring JPA, Spring REST) will now loaded, start pointing to that newly created database which contains users and other stuff data may be on the basis of tenant Id or some other pointing flag.
Further Plan to add 3rd point; 3- oAuth2 rest security as well. so the configuration should be accordingly.
now the question is that how to achieve this in Spring Data JPA application and switch the database configuration on run time?
You can configure multiple data sources upfront in Spring, and segregate associated repositories in different package structures ( not really a switch but accessing multiple data sources from same Spring boot app )
Create a new Configuration to scan repos from a segregated package and also, load the configuration properties to build the second data source.
..create the transaction manager and entity management factory
Finally, access the repositories connecting to different databases.
See complete example here