mybatis-plus实现动态配置实体类表名

mybatis-plus配置文件

在MybatisPlusInterceptor下添加DynamicTableNameInnerInterceptor

@Configuration
@MapperScan(value = {"com.eternity.scrapy.modules.**.mapper*"})
public class MybatisPlusConfig {

    private static ThreadLocal<String> table = new ThreadLocal<>();

    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        //动态设置表名
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        HashMap<String, TableNameHandler> map = new HashMap<String, TableNameHandler>(2) {{
            put("实体类默认设置的表名,按照自己需求修改", (sql, tableName) -> {
                return table.get();
            });
        }};
        dynamicTableNameInnerInterceptor.setTableNameHandlerMap(map);
        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
        return interceptor;
    }

    public static void setDynamicTableName(String tableName) {
        table.set(tableName);
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }
}

在需要动态设置表名的地方,使用MybatisPlusConfig.setDynamicTableName()设置需要动态设置的表名

动态的表名可以放在实体类中,也可以放在数据库中

站在巨人肩膀上摘苹果

https://blog.csdn.net/Dengrz/article/details/121563920

posted @ 2022-05-17 11:03  未月廿三  阅读(1639)  评论(0编辑  收藏  举报