Mybatis-plus实现动态表名查询

 数据库表结构如图所示,现在需要对表进行动态查询,根据自定义的算法找到我们需要查询的表名序号。

 

MybatisPlusConfig配置: 

@Configuration
public class MybatisPlusConfig {

    public static ThreadLocal<String> myTableName = new ThreadLocal<>();

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        HashMap<String, TableNameHandler> map = new HashMap<String, TableNameHandler>(2) {{
            put("t_messages", (sql, tableName) -> {
                return myTableName.get();
            });
        }};
        dynamicTableNameInnerInterceptor.setTableNameHandlerMap(map);
        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
        return interceptor;
    }
}

使用方式,在列表查询前进行动态注入表名即可。

t_message:表示数据库表名

  String t_messages = APiUtil.getTableName("t_message", YEAR, MONTH);
  MybatisPlusConfig.myTableName.set(t_messages);
  List<Messages> list = messagesMapper.selectList(queryWrapper);

 

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页