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

前端 未结 2 1972
不思量自难忘°
不思量自难忘° 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.

    0 讨论(0)
  • 2021-01-03 17:59

    There's no need to get rid of JdbcTemplate. NativeJdbcExtractor was removed in Spring Framework 5 as it isn't needed with JDBC 4.

    You should replace your usage of NativeJdbcExtractor with calls to connection.unwrap(Class). The method is inherited by Connection from JDBC's Wrapper.

    You may also want to consider using AbstractRoutingDataSource which is designed to route connection requests to different underlying data sources based on a lookup key.

    0 讨论(0)
提交回复
热议问题