简体   繁体   中英

Spring boot, JPA dynamic data source connection

I am a newbie to spring , hibernate and JPA .

I have built a project with SpringBoot and JPA . I have a base database which holds different customer database names depending on the customer id. Hence when starting the spring boot application I connect to the base database using JPA repository(straight forward).

Depending on the database name i got in the previous step, i now have to connect to the new database to fetch the customer information using JPA .

Because I don't know the customer database names upfront, i have a problem do this. All the database are MySQL .

Can someone suggest a best way to achieve this?

There are two approachs that you can try.

Approach 1:

You can use DataSourceBuilder to get the DataSource.

DataSource dataSource = DataSourceBuilder.create()  
    .driverClassName(driver-class-name)   
    .url(env.getProperty(dataSoruceUrl).build();
Connection connection = dataSource.getConnection(username, password);

Using connection you can execute the SQL statements.

Approach 2:

You can try AbstractRoutingDatasource provided by Spring. Here is a guide explaining about it.

Hope it helps!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM