Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot: How to use multiple schemas and dynamically choose which one to use at runtime

I have the same question as below, but I want to know the answer. Spring Boot: How to use multiple schemas and dynamically choose which one to use for every request at runtime

Please help me in finding answer for

How can I have one database connection and specify a different schema for every request?

Thank you in advance.

like image 805
AndroidDev Avatar asked Feb 11 '17 18:02

AndroidDev


People also ask

How do I use multiple schemas in spring boot?

Until now with spring 4 and XML configuration I was able to only put the DB URL like: jdbc:mysql://180.179.57.114:3306/?zeroDateTimeBehavior=convertToNull and in the entity class specify the schema to use and thus able to connect to multiple schemas.


1 Answers

Wouldn't it work to have multiple data sources defined, and depending on your request, change to the one with the correct schema?

spring.datasource.url = jdbc:oracle:thin:@//maui:1521/xe
spring.datasource.username = schema1
spring.datasource.password = ...

spring.datasource2.url = jdbc:oracle:thin:@//maui:1521/xe
spring.datasource2.username = schema2
spring.datasource2.password = ..

@Bean
@Primary
@ConfigurationProperties(prefix="spring.datasource")
public DataSource schema1() {
    return DataSourceBuilder.create().build();
}

@Bean
@ConfigurationProperties(prefix="spring.datasource2")
public DataSource schema2() {
    return DataSourceBuilder.create().build();
}

Otherwise you'd need to kill & re-create the connection to keep using the singular data source, but that would be really slow for your application since it would need reconnecting again and again. It would be better for you to use some NoSQL database to achieve this sorta dynamic data storage.

like image 134
buræquete Avatar answered Oct 16 '22 19:10

buræquete