首页 > 其他分享 >若依框架---PageHelper分页(三)

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

时间:2023-02-20 14:04:55浏览次数:40  
标签:若依 拦截器 接口 PageHelper --- PageInterceptor Mybatis class


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

标签:若依,拦截器,接口,PageHelper,---,PageInterceptor,Mybatis,class
From: https://blog.51cto.com/u_15949848/6068477

相关文章