mybatis-PageInterceptor-获取count值

2024-01-07 20:55:02

前言

我们反参是 VO 对象,通过转换后,并不能获取到Count,此时的Count值是 List 的长度,可自行跟下DBUG 就清楚了…

思路

通过继承 PageInterceptor 获取到反参,判断如果是Page则进行转换,然后将其放入到 ThreadLocal 中

拦截器代码

/**
 * 重写 分页,用于获取数据
 */
@Intercepts(
        {
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        }
)
public class SpecialPageInterceptor extends PageInterceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object intercept = super.intercept(invocation);
        // 判断是否为Page
        if (Page.class.equals(intercept.getClass())) {
            Page page = (Page) intercept;
            long total = page.getTotal();
            PageCountThreadLocalUtil.setPageCount(total);
        }
        return intercept;
    }

}

mybatis配置文件配置

<configuration>
    <plugins>
        <plugin interceptor="com.xxxx.config.SpecialPageInterceptor"></plugin>
    </plugins>
</configuration>

PageCountThreadLocalUtil 工具类代码

public class PageCountThreadLocalUtil {

    private final static ThreadLocal<Long> PAGE_COUNT_THREAD_LOCAL = new ThreadLocal<>();


    public static void setPageCount(Long apUser) {
        PAGE_COUNT_THREAD_LOCAL.set(apUser);
    }


    public static Long getPageCount() {
        return PAGE_COUNT_THREAD_LOCAL.get();
    }

    public static void clear() {
        PAGE_COUNT_THREAD_LOCAL.remove();
    }
}
 

注意

如果使用了 PageHelperAutoConfiguration 需要将其去掉或者在启动类上排除 @SpringBootApplication(exclude = { PageHelperAutoConfiguration.class })

后言

如果有更好的实现方式,欢迎大家留言讨论

文章来源:https://blog.csdn.net/vistaed/article/details/135410759
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。