mybatis-plus动态替换表名

1:添加依赖

<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3.4</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-extension</artifactId>
            <version>3.4.3.4</version>
        </dependency>

  

2:定义handler

public class UserTableNameHandler implements TableNameHandler {
    private List<String> tableNames;    //存放需要替换的表

    public UserTableNameHandler(String ...tableNames) {
        this.tableNames = Arrays.asList(tableNames);
    }

    @Override
    public String dynamicTableName(String sql, String tableName) {
        if (this.tableNames.contains(tableName)){
            return tableName + "_01" ;//为符合条件的表名称添加后缀
        }else{
            return tableName;   //表名原样返回
        }
    }
}

  

3:配置拦截器

@Configuration
public class MyBatisConfig{
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        dynamicTableNameInnerInterceptor.setTableNameHandler(new UserTableNameHandler("sys_user"));

        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);

        return interceptor;
    }
}

 

posted @ 2022-09-17 12:58  yshy  阅读(1282)  评论(0编辑  收藏  举报