Springboot 2.3.1 dynamically update Jdbc template's schema in Multi-tenant environment

前端 未结 2 1986
不思量自难忘°
不思量自难忘° 2021-01-03 17:24

My Project is on spring-boot-starter-parent - "1.5.9.RELEASE" and I\'m migrating it to spring-boot-starter-parent - "2.3.1.RELEASE".

This is multi

2条回答
  •  爱一瞬间的悲伤
    2021-01-03 17:49

    When I was running the application in debug mode I saw Spring was selecting Hikari Datasource.

    I had to intercept getConnection call and update schema.

    So I did something like below,

    Created a Custom class which extends HikariDataSource

    public class CustomHikariDataSource extends HikariDataSource {
    @Override
    public Connection getConnection() throws SQLException {
    
        Connection connection =  super.getConnection();
        connection.setSchema(Utilities.getTenantId());
        return connection;
    }
    }
    

    Then in the config class, I created bean for my CustomHikariDataSource class.

     @Bean
    public DataSource customDataSource(DataSourceProperties properties) {
    
        final CustomHikariDataSource dataSource = (CustomHikariDataSource) properties
                .initializeDataSourceBuilder().type(CustomHikariDataSource.class).build();
        if (properties.getName() != null) {
            dataSource.setPoolName(properties.getName());
        }
        return dataSource;
    }
    

    Which will be used by the JdbcTemplate bean.

     @Bean
    @Scope(
            value = ConfigurableBeanFactory.SCOPE_PROTOTYPE,
            proxyMode = ScopedProxyMode.TARGET_CLASS)
    public JdbcTemplate jdbcTemplate() throws SQLException {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }
    

    With this approach, I will have DataSource bean created only once and for every JdbcTemplate access, the proper schema will be updated during runtime.

提交回复
热议问题