文章目录
- 前言
- 思路
- 拦截器代码
- mybatis配置文件配置
- PageCountThreadLocalUtil 工具类代码
- 注意
- 后言
前言
我们反参是 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 {@Overridepublic Object intercept(Invocation invocation) throws Throwable {Object intercept = super.intercept(invocation);// 判断是否为Pageif (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 })
后言
如果有更好的实现方式,欢迎大家留言讨论