baomidou / mybatis-plus

An powerful enhanced toolkit of MyBatis for simplify development
https://baomidou.com
Apache License 2.0
16.12k stars 4.26k forks source link

在添加了PaginationInnerInterceptor后,无法对查询的数据作特殊处理 #6244

Open chaobingliu opened 1 month ago

chaobingliu commented 1 month ago

当前使用版本 3.5.5

当前环境信息 例如: Java8 + Mysql5.7

描述bug现象 在添加了PaginationInnerInterceptor后,自定义了一个新的InnerInterceptor拦截器,并在其中实现了willDoQuery方法,会导致分页功能失效。

提供问题复现步骤

在添加了PaginationInnerInterceptor后,自定义了一个新的InnerInterceptor拦截器,在其中实现了willDoQuery方法,代码如下:

@Override
public boolean willDoQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    List<Object> resultList = executor.query(ms, parameter, rowBounds, resultHandler);
    resultList.forEach(entity -> System.out.println(entity));
    return false;
}

但这样做会导至分页功能失效。

提供完整堆栈日志(可选)

提供问题复现工程(可选) 请尽量提供复现工程,减少大家排错的时间.

chaobingliu commented 1 month ago

老师,如果通过实现InnerInterceptor接口无法实现对查询的数据作处理,请问有什么好的方法可以达到相同的目的呢?

chaobingliu commented 1 month ago

我想可能是因为executor.query多次执行导致的,但如果不执行executor.query的话,该怎么获取到查询的数据呢?

xxx-tea commented 1 month ago

InnerInterceptor本来就是对sql进行拦截修改的,如果你想不影响分页功能的话做一写sql记录的话,可以使用mybaits的Interceptor来进行拦截,可以参考下我以前写过的

@Configuration public class MyBatisPlusConfig {

@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
    mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
    return mybatisPlusInterceptor;
}

@Bean
public ConfigurationCustomizer configurationCustomizer() {
    return configuration -> configuration.addInterceptor(new TagFillInterceptor());
}

}

@Intercepts(@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})) public class TagFillInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { // 先执行查询,获取结果 Object result = invocation.proceed(); // 对查询结果进行处理,填充List if (result instanceof List) { List<?> resultList = (List<?>) result; if (!resultList.isEmpty() && resultList.get(0) instanceof Course) { fillTags(resultList); } } return result; }

private void fillTags(List<?> entities) {
    TagService tagService = SpringUtil.getBean(TagService.class);
    for (Object entity : entities) {
        Course course = (Course) entity;
        List<String> tagList = course.getTagList();
        if (CollUtil.isNotEmpty(tagList)) {
            List<Tag> tags = tagService.listByIds(tagList);
            course.setTags(tags);
        }
    }
}

@Override
public Object plugin(Object target) {
    return Plugin.wrap(target, this);
}

}