Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

403
Views
Creating Datasource Dynamically in SpringBoot OpenJPA Application (Implementing Multitenancy with OpenJPA)

I am creating a Springboot application with OpenJPA.

My requirement is that I need to connect to multiple datasources dynamically and the datasource credentials are obtained at runtime by calling some rest-endpoints.

Here is the controller class:

@RestController
public class StationController {

@Autowired
BasicDataSource dataSource;

I have a service which returns me the jdbc_url depending on the customer name:

public String getDSInfo(String customername){
    // code to get the datasource info (JDBC URL)
} 

My questions are:

  1. Is there a way in which I can create datasources at runtime by getting datasource credentials by calling some other service (which takes the customer id and returns the customer specific datasource) ?

  2. Since my application is a web based application, many customers will be accessing it at the same time, so how to create and handle so many different datasources?

NOTE:

  1. The code will get information about the customer specific data source only by firing some service at the runtime, so I cannot hardcode the datasource credentials in the XML configuration file.

  2. I found some implementations with Hibernate but i am using Springboot with OpenJPA. So need OpenJPA specific help.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

It sounds like you want a multi-tenancy solution.

Datasources are easy to create programmatically, just use a DataSourceBuilder with your connection details pulled in from a central source (e.g. a central config database or Spring Config Server).

Then you'll need to look at a multi-tenancy framework to tie the datasources back to clients.

See here:

https://www.youtube.com/watch?v=nBSHiUTHjWA

and here

https://dzone.com/articles/multi-tenancy-using-jpa-spring-and-hibernate-part

The video is a long watch but a good one. Basically you have a map of customer data sources (from memory) that allow an entityManager to pick up a datasource from the map by using a thread scoped custom spring scope of "customer" which is set when a user for a particular customer somehow logs into your app.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!