mybatis-plus 动态表名简易使用

场景:由于有些表是分表的,需要给表名添加后缀才能正确地访问表,如sys_user_2024_01

代码

依赖版本

xml 复制代码
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3.4</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-extension</artifactId>
            <version>3.4.3.4</version>
            <scope>compile</scope>
        </dependency>

mybatisplus配置类

java 复制代码
/**
 *  MybatisPlus 配置文件
 */
@Configuration
@MapperScan({"com.xxx.dataana.mapper"})
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        //动态表名实现
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        //可以传多个表名参数,指定哪些表使用TableNameSuffixHandler处理表名称
        dynamicTableNameInnerInterceptor.setTableNameHandler(new TableNameSuffixHandler("sys_user"));
        //以拦截器的方式处理表名称
        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);

        return interceptor;
    }

TableNameSuffixHandler

java 复制代码
/**
 * mybatis-plus 成动态表名控制器
 */
public class TableNameSuffixHandler implements TableNameHandler {
    /**
     * 用于记录哪些表可以使用该动态表名处理器(即哪些表需要分表)
     */
    private final List<String> tableNames;

    /**
     * 构造函数,构造动态表名处理器的时候,传递tableNames参数
     * @param tableNames
     */
    public TableNameSuffixHandler(String... tableNames) {
        this.tableNames = Arrays.asList(tableNames);
    }

    /**
     * 每个请求线程维护一个suffix数据,避免多线程数据冲突。所以使用ThreadLocal
     */
    private static final ThreadLocal<String> TABLE_SUFFIX = new ThreadLocal<>();

    /**
     * 设置请求线程的表名后缀数据
     * @param tableNameSuffix
     */
    public static void setSuffix(String tableNameSuffix) {
        TABLE_SUFFIX.set(tableNameSuffix);
    }

    /**
     * 删除请求线程的表名后缀数据
     * 注: 使用完必须释放
     */
    public static void removeSuffix() {
        TABLE_SUFFIX.remove();
    }

    /**
     * 动态表名接口实现方法
     * @param sql
     * @param tableName
     * @return
     */
    @Override
    public String dynamicTableName(String sql, String tableName) {
        if (this.tableNames.contains(tableName)) {
            String suffix = TABLE_SUFFIX.get();
            if(suffix != null){
                //表名增加后缀
                return tableName + suffix;
            }
        }
        //表名原样返回
        return tableName;
    }
}

使用

java 复制代码
    public ServiceResponse deleteRelaEventByRelaId(String anaVerId, String relaId) {
        LambdaUpdateWrapper<SysUser> luw = Wrappers.lambdaUpdate(SysUser.class)
                .set(SysUser::getStatus, "0")
                .set(SysUser::getUpdateTime, new Date())
                .eq(SysUser::getId, relaId);
        TableNameSuffixHandler.setSuffix("_2024_01");
        this.update(luw);
        TableNameSuffixHandler.removeSuffix();
        return ServiceResponse.createSuccess();
    }

参考:

相关推荐
人生偌只如初见3 分钟前
NebulaGraph学习笔记-SessionPool之getSession
java·graph·nebula·session·pool
五行星辰6 分钟前
SpringBoot与Redis联姻:从青铜到王者的配置婚庆指南!
java·后端
小园子的小菜12 分钟前
探秘 Netty 通信中的 SslHandler 类:保障网络通信安全的基石
java·安全·web安全·netty
五行星辰16 分钟前
Redisson:Redis界的变形金刚,会变身还会唱跳Rap!
java·后端
BUG研究员_17 分钟前
Spring Boot自动装配原理
java·spring boot·后端
嘵奇18 分钟前
MyBatis-Plus 注解大全
java·mybatis
五行星辰19 分钟前
Jedis大战Redis:码农版《星球大战》开演
java·后端
zlt200042 分钟前
Spring AI与DeepSeek实战二:打造企业级智能体
人工智能·spring boot·deepseek
七七powerful1 小时前
ClickHouse 中出现 DB::Exception: Too many parts 错误
java·前端·数据库
伯牙碎琴1 小时前
十一、Spring Boot:使用JWT实现用户认证深度解析
java·spring boot·后端