问题描述
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("========================");
}
}
}
}
添加自定义动态表名拦截器