mybatis-plus的多数据源sql拦截&动态表名

问题描述

1、我们使用的是mybatis-plus的多数据源链接,之前使用的mybatis-plus版本是3.3.1(版本低了,用不了)
2、在网上找的诸多的sql拦截代码,发现断点进不去,找原因后发现由于配置的多个数据源,所以有多个SqlSessionFactory,只有其中的default中有我们添加的sql拦截器,我们最终的解决方案是遍历所有的SqlSessionFactory,删除其中的MybatisPlusInterceptor,再添加我们自定义的MybatisPlusInterceptor

mybatis-plus版本依赖

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

删除所有MybatisPlusInterceptor,再添加自定义的MybatisPlusInterceptor

@Component
@SuppressWarnings("SpringJavaAutowiredMembersInspection")
public class InterceptorConfig implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired(required = false)
    private List<SqlSessionFactory> sqlSessionFactoryList;
    @Autowired(required = false)
    private MybatisPlusInterceptor mybatisPlusInterceptor;


    @Override
    @SuppressWarnings("unchecked")
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (CollectionUtils.isNotEmpty(sqlSessionFactoryList) && Objects.nonNull(mybatisPlusInterceptor)) {
            try {
                for (SqlSessionFactory factory : sqlSessionFactoryList) {
                    Field interceptorChain = Configuration.class.getDeclaredField("interceptorChain");
                    interceptorChain.setAccessible(true);
                    InterceptorChain chain = (InterceptorChain) interceptorChain.get(factory.getConfiguration());
                    Field interceptors = InterceptorChain.class.getDeclaredField("interceptors");
                    interceptors.setAccessible(true);
                    List<Interceptor> list = (List<Interceptor>) interceptors.get(chain);
                    if (CollectionUtils.isNotEmpty(list)) {
                        if (list.get(list.size() - 1) != mybatisPlusInterceptor) {
                            list.removeIf(i -> i == mybatisPlusInterceptor);
                            list.add(mybatisPlusInterceptor);
                        }
                    } else {
                        list.add(mybatisPlusInterceptor);
                    }
                }
            } catch (Exception ignored) {
                System.out.println("========================");
            }
        }
    }
}

添加自定义动态表名拦截器
在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值