Loading

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);

 

posted @ 2023-01-04 10:38  Roc-xb  阅读(506)  评论(0编辑  收藏  举报

易微帮源码


易微帮官网