若依系统分页工具学习-PageHelper篇三

988 阅读2分钟

这是我参与11月更文挑战的第14天,活动详情查看:2021最后一次更文挑战

在上一篇文章“若依系统分页工具学习-PageHelper篇二”中,我们阐述了PageHelper使用ThreadLocal来将分页参数保存在当前线程中。那么我们为什么却找不到若依项目中后续添加拦截器的代码呢?

PageHelper-Spring-Boot-Starter

若依是基于SpringBoot的。而PageHelper有一个spring-boot版本PageHelper-Spring-Boot-Starter

我们下载其源码来看看。

该项目中最重要的一个类是PageHelperAutoConfiguration,其部分源代码如下所示:

/**
 * 自定注入分页插件
 *
 * @author liuzh
 */
@Configuration
@ConditionalOnBean(SqlSessionFactory.class)
@EnableConfigurationProperties(PageHelperProperties.class)
@AutoConfigureAfter(MybatisAutoConfiguration.class)
@Lazy(false)
public class PageHelperAutoConfiguration implements InitializingBean {
    // 其他代码
}

如此便通过注解便将该拦截器PageInterceptor注入到项目中。PageInterceptor的部分代码如下:

public class PageInterceptor implements org.apache.ibatis.plugin.Interceptor {
    // 类内的其他代码...
}

该插件实现了接口org.apache.ibatis.plugin.Interceptor,这个接口又是干嘛的呢?

Mybatis拦截器接口

PageHelper中的拦截器PageInterceptor实现了接口org.apache.ibatis.plugin.Interceptor,后者实际为Mybatis的拦截器接口。

实现了该接口的拦截器可以拦截Mybatis执行请求,修改Mybatis的默认行为,例如重写Sql。

哇,这不就是我们一直在找的逻辑吗?

我们来以PageInterceptor为例看看Mybatis的拦截器接口一般情况下式如何实现:

/**
 * Mybatis - 通用分页拦截器
 * <p>
 * GitHub: https://github.com/pagehelper/Mybatis-PageHelper
 * <p>
 * Gitee : https://gitee.com/free/Mybatis_PageHelper
 *
 * @author liuzh/abel533/isea533
 * @version 5.0.0
 */
@SuppressWarnings({"rawtypes", "unchecked"})
@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 PageInterceptor implements Interceptor {
    
     @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 拦截器逻辑代码...
    }
}

有一个很有意思的注解:@Intercepts

通过搜索资料,我们知道了该注解中的type可取值为:Executor.class, StatementHandler.class,PameterHandler.class, ResultSetHandler.class。

这里我们暂时不展开讲述接口的实现,大家可以对其实现,尤其是这一个注解,保留一个基础的印象。

现在,我们捋一下,就是PageHelper插件中的PageInterceptor通过实现接口org.apache.ibatis.plugin.Interceptor,从而达到了重新SQL的目的。

返回去,我们再去查看拦截器中是如何具体实现重新SQL达到分页目的的。