[SOLVED] Create Multipe Jdbctemplate at runtime pointing to diffrent databases in runtime

Issue

Spring boot Is there any way to create Jdbctemplate at runtime pointing to the different MySQL databases?

Runtime I do have all the required information.

The database structure is the same for all the clients but the instance is different.

I also tried with How to create multiple Jdbctemplate beans, pointing to different Mysql databases, in runtime?
but not able to find any solution.

Solution

I guess this can be done like this:

@Component
public class JdbcTemplateProvider {

    private final Map<String, DataSource> databaseNameToDataSourceMap;
    private final JdbcProperties properties;

    public JdbcTemplateProvider(List<DataSource> dataSources, JdbcProperties properties) {
        this.databaseNameToDataSourceMap = this.buildDatabaseToDataSourceMap(dataSources);
        this.properties = properties;
    }

    public JdbcTemplate byDatabaseName(String database) {
        DataSource dataSource = this.databaseNameToDataSourceMap.get(database);
        return buildJdbcTemplate(dataSource);
    }

    private Map<String, DataSource> buildDatabaseToDataSourceMap(List<DataSource> dataSources) {
        return new ConcurrentHashMap<>();
    }

    private JdbcTemplate buildJdbcTemplate(DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        JdbcProperties.Template template = properties.getTemplate();
        jdbcTemplate.setFetchSize(template.getFetchSize());
        jdbcTemplate.setMaxRows(template.getMaxRows());
        if (template.getQueryTimeout() != null) {
            jdbcTemplate.setQueryTimeout((int) template.getQueryTimeout().getSeconds());
        }
        return jdbcTemplate;
    }

}

If this question was if Spring Boot can natively handle this, as far as I know there may not be any built in solution for this.

org.springframework.boot.autoconfigure.jdbc.JdbcProperties reads properties values with prefix spring.jdbc.If it is available in your classpath, this will be able to configure newly built JdbcTemplate instances as per configuration.

You will have build your own logic though to build map of database name to datasource.

Answered By – Gaurav

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.