全局拦截mybatis-Plus 替换HAS_SUB_TABLE_NAME
中表名
package com.sumwhy.fly.service.order.center.service.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.sumwhy.fly.service.order.center.service.entity.OcShopOrder;
import com.sumwhy.fly.service.order.center.service.entity.OcShopOrderChild;
import com.sumwhy.fly.service.order.center.service.helper.DynamicTableHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
/**
* 描述:
*
* @author yjj
* @date 2021/12/13 15:10
*/
@Configuration
public class MybatisPlusInterceptorConfig {
private static final String[] HAS_SUB_TABLE_NAME = new String[]{
OcShopOrder.shopOrder, OcShopOrderChild.shopOrderChild
};
@Autowired
public void onSetInterceptor(MybatisPlusInterceptor interceptor) {
DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
dynamicTableNameInnerInterceptor.setTableNameHandler((sql, tableName) -> {
for (String s : HAS_SUB_TABLE_NAME) {
if (s.equalsIgnoreCase(tableName)) {
return DynamicTableHelper.resolveSubTableByBrand(DynamicTableHelper.getBrandId(), tableName);
}
}
return tableName;
});
List<InnerInterceptor> interceptors = new ArrayList<>();
interceptors.add(dynamicTableNameInnerInterceptor);
interceptors.addAll(interceptor.getInterceptors());
interceptor.setInterceptors(interceptors);
}
}
全局设置分表号
package com.sumwhy.fly.service.order.center.service.helper;
import com.sumwhy.sumwhyfly.common.core.BaseException.BaseException;
import org.apache.commons.lang3.StringUtils;
import java.util.Objects;
/**
* 描述:
*
* @author yjj
* @date 2021/12/13 15:19
*/
public class DynamicTableHelper {
private static final ThreadLocal<String> CURRENT_BRAND_ID = new ThreadLocal<>();
public static String resolveSubTableByBrand(String brandId, String table) {
return table + "_" + brandId;
}
public static void setBrandId(String brandId) {
Objects.requireNonNull(brandId);
CURRENT_BRAND_ID.set(brandId);
}
public static String getBrandId() {
String brandId = CURRENT_BRAND_ID.get();
if (StringUtils.isBlank(brandId)) {
throw new BaseException("current thread brandId not set");
}
return brandId;
}
public static void removeBrandId() {
CURRENT_BRAND_ID.remove();
}
}