Search code examples
springdatabasespring-bootspring-data-jpadatasource

Read datasource from a database or a file and based on API identifier, save data in the database? Which tool to use?


In a Spring Boot Application, there is a method mapped with a POST API for posting certain data in database. The issue is based on API URL parameter, data source will change.

Like the API is: {baseURL}/api/{someIdentifier}/addUser

Now, there is another file or consider a database which maps Database Connection Strings (like Datasource, Username, password, driver) to this {someIdentifier}. There could be a lot of such identifiers (corresponding to which there could be multiple databases and their parameters).

Now when this API gets hit, based on this identifier there will be a method which will fetch connection strings, make the connection and then it should save the data in that database. On every API, creating a connection is not feasible.

Can anyone please suggest which tool or technology can be helpful for solving this problem, especially using Spring Boot.

Thanks in advance!


Solution

  • You are looking for the AbstractRoutingDataSource.

    From its documentation:

    Abstract DataSource implementation that routes getConnection() calls to one of various target DataSources based on a lookup key. The latter is usually (but not necessarily) determined through some thread-bound transaction context.