package cc.admin.config.mybatis;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
public class TenantTableNameHandler implements TableNameHandler {
/**
* 每个请求线程维护一个数据,避免多线程数据冲突。所以使用ThreadLocal
*/
private static final ThreadLocal<String> SUFFIX = new ThreadLocal<>();
/**
* 设置请求线程的month数据
* @param suffix
*/
public static void setData(String suffix) {
SUFFIX.set(suffix);
}
@Override
public String dynamicTableName(String sql, String tableName) {
System.out.println("sql:" + sql);
String suffix = SUFFIX.get();
if (StrUtil.isNotEmpty(suffix)) {
SUFFIX.remove();
System.out.println("suffix:" + suffix);
System.out.println("动态查询表:" + tableName + suffix);
return tableName + suffix;
}
return tableName;
}
}
调用方法
@Override
public Page<Student> selectByPage() {
Page<Student> page = PageController.getPageByRequest(request);
MyTableNameHandler.setData("_2021");//此处调用方法
return this.baseMapper.selectPage(page, null);
}
注册插件
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//prevent delete All
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());//防止改、删全表
DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
dynamicTableNameInnerInterceptor.setTableNameHandler(new MyTableNameHandler());//动态表名插件
interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//分页插件
return interceptor;
}
}