Connecting dynamically to different databases using spring boot

Viewed 5445

How can I connect to multiple databases which are non-identical on the fly (loading the type and connection info of the DB from my DB) using Spring?

what I am trying to build?
I am building a Spring-Boot application that should be able to get data from my customers in the following ways:
1. Connect to my customer SQL DB (MySQL, MSSQL, PostgreSQL,etc...)
2. connect to my customer MongoDB,
3. read data from CSV/JSON files.

While the app is running it gets an HTTP request with customer id. to connect to. at this point, the app should load this customer from my DB (that contain exactly what DB he's using and the credentials to connect to it) and should init a connection to this DB to be able to start query it. (DB Schemas are different between 1 customer to another so I also maintain a set of queries in my DB to query the customer)

I'm struggling to implement the blue part of the diagram:

I'm struggling to implement the blue part of the diagram

2 Answers

It is possible to create JdbcTemplate on the fly to query the MySQL database. The following example shows how to do it:

DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://host:port/database");
dataSource.setUsername("username");
dataSource.setPassword("password");

JdbcTemplate template = new JdbcTemplate(dataSource);
SqlRowSet sqlRowSet = template.queryForRowSet("SELECT FOO FROM BAR;");

A similar approach can be used to work with MongoDB — create MongoTemplate to work with data. Another way is to use the native MongoDB library. Here you can find more information on how to use it.

If the libraries from Spring Boot are used don't forget to disable autoconfiguration, because there are no credentials on startup.

You can configure multiple data sources in you application. All you need is to mention their driverClassName connectionUrl username password. You can find an example here

PS: Don't forget to mention their dependencies

Related