0

spring works well when we use the default datasource and ways we can use in-build spring jpa.

So currently what we do is the following

specify the config for DB in the application.properties

myapp.datasource.url=jdbc:mysql:thin:@localhost:1521:myschema
myapp.datasource.username=user
myapp.datasource.password=password
myapp.datasource.driver-class=com.mysql.cj.jdbc.Driver

Custom datasource

@ConfigurationProperties(prefix = "myapp.datasource")
@Bean
public DataSource mySqlDataSource() 
{
    return DataSourceBuilder.create().build();
}

We have the same application running for multiple clients. Problem is each client has their own DB schema.

So, the problem now is that we need to be able to serve each client but in order to do this, we need to create multiple datasources for instance:

@ConfigurationProperties(prefix = "myapp.partner1.datasource")
@Bean
public DataSource mySqlDataSourcePartner1() 
{
    return DataSourceBuilder.create().build();
}

@ConfigurationProperties(prefix = "myapp.partner2.datasource")
@Bean
public DataSource mySqlDataSourcePartner2() 
{
    return DataSourceBuilder.create().build();
}

@ConfigurationProperties(prefix = "myapp.partner3.datasource")
@Bean
public DataSource mySqlDataSourcePartner3() 
{
    return DataSourceBuilder.create().build();
}

and so on...

Is there a generic and more efficient way of doing this? where if in future when a new partner is added we can just specify the config in application properties and get that working?

Vicky
  • 104
  • 1
  • 9
  • How about using multitenant approach? – bananas Nov 23 '19 at 12:54
  • how do you decide which data source to use? – dassum Nov 23 '19 at 16:52
  • @dassum by the id of the partner in the passed request. – Vicky Nov 23 '19 at 17:08
  • @emotionlessbananas can you please elaborate more or point me to some references please? – Vicky Nov 23 '19 at 17:12
  • I think your approche, even verbose, is the best way to go. You don't provide enough info but I suppose that your entities are not the same in all datasources, so i f you want to keep some customisation I suggest you to not change your approche. – akuma8 Nov 23 '19 at 17:30
  • https://www.google.com/amp/s/blog.aliprax.me/schema-based-multitenancy/amp/ you can even search more. I cannot remember the blog I used to implement this. But this is a good starting point – bananas Nov 25 '19 at 02:07

1 Answers1

0

You can use Spring Boot Multi-tenancy model using a separate database for each client. You can save the database configuration in config-properties or database then depending upon the ClientId you can you the Datasource. You need to add Interceptor to intercept the Request and identify the tenant. Please refer to the below example

https://tech.asimio.net/2017/01/17/Multitenant-applications-using-Spring-Boot-JPA-Hibernate-and-Postgres.html

please check

https://github.com/sumanentc/multitenant

dassum
  • 4,727
  • 2
  • 25
  • 38