2024-11-14 13:05:57 +08:00
|
|
|
|
package net.shapelight.common.handler;
|
2024-11-11 16:56:43 +08:00
|
|
|
|
|
|
|
|
|
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
|
|
|
|
|
|
|
|
|
|
import java.util.Arrays;
|
|
|
|
|
import java.util.List;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 按自定义字段参数,组成动态表名
|
|
|
|
|
*/
|
|
|
|
|
public class CustomizeTableNameHandler implements TableNameHandler {
|
|
|
|
|
//用于记录哪些表可以使用该月份动态表名处理器(即哪些表可以分表)
|
|
|
|
|
private List<String> tableNames;
|
|
|
|
|
|
|
|
|
|
//构造函数,构造动态表名处理器的时候,传递tableNames参数
|
|
|
|
|
public CustomizeTableNameHandler(String ...tableNames) {
|
|
|
|
|
this.tableNames = Arrays.asList(tableNames);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//每个请求线程维护一个分表字段数据,避免多线程数据冲突。所以使用ThreadLocal
|
|
|
|
|
private static final ThreadLocal<String> CELL_DATA = new ThreadLocal<>();
|
|
|
|
|
|
|
|
|
|
//设置请求线程的month数据
|
|
|
|
|
public static void setData(String month) {
|
|
|
|
|
CELL_DATA.set(month);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//删除当前请求线程的month数据
|
|
|
|
|
public static void removeData() {
|
|
|
|
|
CELL_DATA.remove();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//动态表名接口实现方法
|
|
|
|
|
@Override
|
|
|
|
|
public String dynamicTableName(String sql, String tableName) {
|
|
|
|
|
if (this.tableNames.contains(tableName)){
|
|
|
|
|
return tableName + "_" + CELL_DATA.get(); //表名增加分表字段后缀
|
|
|
|
|
}else{
|
|
|
|
|
return tableName; //表名原样返回
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|