场景: 当一个业务数据量比较大了,通常都会采用分表分库的方式进行数据存放,但我们通常使用的mybatis-Plus表名是通过注解写死的,当我们想查询不同表明之间的数据
1 老老实实得写sql,表明通关动态传值
2 配置mybatis-plus动态表名
注:比较懒,实在懒得就写sql
Mybatis-Plus 动态表名配置实现
1 打开官网 官网地址:https://baomidou.com/ 搜索 “动态表名”
2 会看见动态表名插件,进入示例会看见源码
根据自己的需求实现就好,不过得注意一点在配置mybatis时,一定要将DynamicTableNameInnerInterceptor添加进MybatisPlusInterceptor放到分页插件之前,不然select
count(*) xxx 多少条数据是不会替换表名的
我自己的代码
/**
* @author tzw
* @description 请求参数传递辅助类
* @date 2022.11.7 20:28
*/
public class TableNameHelper {
public static final ThreadLocal<String> REQUEST_DATA = new ThreadLocal<>();
public static void setTableName(String tableName){
REQUEST_DATA.set(tableName);
}
public static String getTableName(){
return REQUEST_DATA.get();
}
}
/**
* mybatis-plus配置
*
* @author Mark [email protected]
* @since 1.0.0
*/
@Configuration
public class MybatisPlusConfig {
private static ThreadLocal<String> myTableName = new ThreadLocal<>();
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
// 动态表名
DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
dynamicTableNameInnerInterceptor.setTableNameHandler(new DynamicEntityTableNameHandler());
mybatisPlusInterceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
// 数据权限
mybatisPlusInterceptor.addInnerInterceptor(new DataFilterInterceptor());
// 分页插件
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
// 乐观锁
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
// 防止全表更新与删除
mybatisPlusInterceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
// 返回
return mybatisPlusInterceptor;
}
}
/**
* @author tzw
* @description 动态表名
* @date 2022.11.7 19:44
*/
public class DynamicEntityTableNameHandler implements TableNameHandler {
/**
* 自定义动态表名
* @param sql 当前执行 SQL
* @param tableName 表名 entity里注解传入的表明
* @return
*/
@Override
public String dynamicTableName(String sql, String tableName) {
System.out.println(tableName);
if (Objects.equals(tableName, "talk_log_table")){
return TableNameHelper.getTableName();
}
return tableName;
}
}
/**
*
*
* @author tianzhiwu [email protected]
* @since 1.0.0 2022-11-07
*/
@Service
public class TalkLogTableServiceImpl extends CrudServiceImpl<TalkLogTableDao, TalkLogTableEntity, TalkLogTableDTO> implements TalkLogTableService {
@Override
public QueryWrapper<TalkLogTableEntity> getWrapper(Map<String, Object> params){
TableNameHelper.setTableName(getTalkLogTable(new Date()) );
String id = (String)params.get("id");
QueryWrapper<TalkLogTableEntity> wrapper = new QueryWrapper<>();
wrapper.eq(StringUtils.isNotBlank(id), "id", id);
return wrapper;
}
private String getTalkLogTable(Date date){
String yyyyMMdd = DateUtil.format(new Date(), "yyyyMMdd");
return "cq_event_log.talk_log_table_" + yyyyMMdd;
}
}