若依框架---PageHelper分页(三)

简介: 若依框架---PageHelper分页(三)

在上一篇文章“若依系统分页工具学习-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达到分页目的的。


目录
相关文章
|
2月前
|
SQL Java 数据库连接
若依框架---PageHelper分页(四)
若依框架---PageHelper分页(四)
86 0
|
2月前
|
SQL 数据库
若依框架---PageHelper分页(六)
若依框架---PageHelper分页(六)
74 0
|
2月前
|
SQL Oracle 关系型数据库
若依框架---PageHelper分页(七)
若依框架---PageHelper分页(七)
69 0
|
2月前
|
SQL Java 关系型数据库
若依框架---PageHelper分页(十一)
若依框架---PageHelper分页(十一)
92 0
|
2月前
|
SQL Oracle 关系型数据库
若依框架---PageHelper分页(五)
若依框架---PageHelper分页(五)
75 0
|
2月前
|
SQL Java 关系型数据库
PageHelper分页插件最新源码解读及使用
PageHelper分页插件最新源码解读及使用
|
2月前
|
前端开发 关系型数据库 MySQL
springboot+jpa+tymeleaf实现分页功能
springboot+jpa+tymeleaf实现分页功能
18 0
|
2月前
|
SQL 缓存
若依框架---PageHelper分页(八)
若依框架---PageHelper分页(八)
40 0
|
2月前
|
SQL 安全 Java
若依框架---PageHelper分页(二)
若依框架---PageHelper分页(二)
103 0
|
2月前
|
SQL 监控 Java
若依框架---PageHelper分页(十)
若依框架---PageHelper分页(十)
71 0