0
votes

I want to load multitenant database from a database not from properties file. I am following this tutorial (https://fizzylogic.nl/2016/01/24/make-your-spring-boot-application-multi-tenant-aware-in-2-steps/). This is how my DataSource Bean looks like:

    @Bean
    public DataSource dataSource() {
        Map<Object, Object> resolvedDataSources = this.multiTenantDbBuilder.getResolvedDataSources();
        TenantAwareRoutingSource dataSource = new TenantAwareRoutingSource();
        dataSource.setDefaultTargetDataSource(this.defaultDataSource());
        dataSource.setTargetDataSources(resolvedDataSources);
        dataSource.afterPropertiesSet(); // Call this to finalize the initialization of the data source.
        return dataSource;
    }

I would like to retrieve my resolvedDataSources from a database (the default one), the problem is that i am not able to use JPA because DataSource bean has not been created already.

Thank you all !

1

1 Answers

1
votes

Such an implementation is a bit complicated than it seemed at first glance - It's neccesary to create two datasources: one for AbstractRoutingDataSource (a 'multi-database' datasource), the second - for the database where the tenant properties are stored (in this style).

You can find the working example in this branch of my demo project: tenant-in-db.

To run the branch - first start Postgres with docker-compose.yml - it creates predefined tenant DBs, then run Application. After that you will be able to run demo requests in api-demo.http (if you are using IntelliJ IDEA).


My original post about multi-tenancy.