How to switch Database on runtime in SpringBoot and SpringDataJPA / Hibernate?
Asked Answered
B

0

3

I want to create an application with SpringBoot, SpringRest, SpringDataJPA / Hibernate with multiple databases on runtime.

Actually i am creating multitenant application with following flow:

1- one Applcation may be php: from website user will create account, the system will run the process and will create database and releated configuration.

2- Major application ( SpringBoot, SpringRest, SpringDataJPA / hibernate ) will now loaded start pointing to that newly created database which contains users and other stuff data.

3- I want to add oauth2 rest security as well. so the configuration should be acordingly.

now the question is that how to achieve this in springBoot and springDataJPA application and swtich the database configuration on runtime?

your answers are highly appreciated.

thanks.

Braasch answered 14/11, 2018 at 9:48 Comment(9)
the following website provide very good tutorials callicoder.com/categories/spring-bootHanahanae
this is not answer of my question. i dont have issue in springBoot, i want to develop a strategy of switching database on runtime @SamimBraasch
First app can write the db info (port, connection, user, password) to application.properties of SpringBoot (or any other conf file) then spring boot after spin up can read db info from that config file. Just a thought haven't done it myself.Netti
@irfanNasim Check this link. It also mentions the same approach with context reloadingNetti
#39357867Netti
Hi Irfan, am I understanding you correctly: you create a new database for every single user? So the question would be: On which basis do you want to switch the "database"? Basically my answer @NaumanRafique posted goes to that direction. It can be adjusted to work with complete different databases and schemes. But the requirement is: they have to follow the same schema. So your entities will match.Algia
@IrfanNasim I would recommend that you have a util class that has a method that accepts the JDBC URL, username and password and returns a DataSource object configured with those. So when a user logs in, there is a public table that has the mapping of the JDBC URL and account name which should correspond to the DB you want to connect to. Then you persist this in the session by setting it in the context. Do you give a unique URL to your customers or how is your design?Laynelayney
@SimonMbatia agreed with your solution and implemented and created an application which is running perfect, i will provide same url to the customer but with unique orgId / TenantId on login screen.Braasch
@SimonMbatia now i have another application to refactored towards above approach which is ORM base. i believe ORM dont support this type of things i have to re write the data layer. what you suggest ?Braasch

© 2022 - 2024 — McMap. All rights reserved.