mybatisplus动态表名

一、首先添加pom依赖

     
            com.baomidou
            mybatis-plus-extension
            3.4.3
        

二、添加entity

注意:entity不能是entity结尾这样的,就要原样写表名,不然会有问题

mybatisplus动态表名_第1张图片

三、接下来新建一个配置类

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configuration
public class MybatisPlusConfig {
    public static ThreadLocal myTableName = new ThreadLocal<>();
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        HashMap map = new HashMap(2) {{
            put("acct_item_total_month", (sql, tableName) -> {
                return myTableName.get();
            });
        }};
        dynamicTableNameInnerInterceptor.setTableNameHandlerMap(map);
        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
        return interceptor;
    }
}

四、然后是mapper

@CacheNamespace
public interface AcctItemTotalMonthMapper extends BaseMapper {

}

 五、然后我们新建一个测试类就可以测试动态表名查询了

@Service
@DS("acctdb")
public class AcctItemTotalMonthServiceImpl extends ServiceImpl implements AcctItemTotalMonthService {

    public void query1(){

        MybatisPlusConfig.myTableName.set("acct_item_total_month_202304");//这里偷懒了直接输入的,大家自便
        QueryWrapper queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("acct_item_id", "2");

        List entities = this.list(queryWrapper);

        for (AcctItemTotalMonth entity : entities) {
            System.out.println("entity:"+entity);
        }
    }

}

参考:https://mp.csdn.net/mp_blog/creation/editor?spm=1001.2014.3001.4503

你可能感兴趣的:(mybatis,java,mysql)