package com.gkhy.hazmat.common.config; import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler; import com.gkhy.hazmat.common.utils.StringUtils; import java.util.HashMap; import java.util.Map; /** * 自定义动态表名处理器,基于id的方式进行分表 */ public class IdTableNameHandler implements TableNameHandler { private static final Map CONFIG_TABLE_INFO_MAP=new HashMap<>(); static { CONFIG_TABLE_INFO_MAP.put("hz_hazmat",20); CONFIG_TABLE_INFO_MAP.put("hz_hazmat_flow",20); CONFIG_TABLE_INFO_MAP.put("hz_product",20); CONFIG_TABLE_INFO_MAP.put("hz_product_flow",20); } private static final ThreadLocal ID_DATA=new ThreadLocal<>(); @Override public String dynamicTableName(String sql, String tableName) { if(StringUtils.isBlank(tableName)||!CONFIG_TABLE_INFO_MAP.containsKey(tableName)){ return tableName; } //分表个数 int tableSize=CONFIG_TABLE_INFO_MAP.get(tableName); //当前分表的id Long currentId=getCurrentId(); if(currentId==null){ throw new RuntimeException("请设置分表id值"); } int tableIndex= (int) (currentId%tableSize); //清理当前id // removeCurrentId(); return tableName+"_"+tableIndex; } /** * 获取当前分表id * @param id */ public static void setCurrentId(Long id){ ID_DATA.set(id); } public static Long getCurrentId(){ return ID_DATA.get(); } public static void removeCurrentId(){ ID_DATA.remove(); } }