今天和大家分享下mybatis的一个分页插件PageHelper,在讲解PageHelper之前我们需要先了解下mybatis的插件原理。PageHelper

的官方网站:https://github.com/pagehelper/Mybatis-PageHelper

一、Plugin接口

mybatis定义了一个插件接口org.apache.ibatis.plugin.Interceptor,任何自定义插件都需要实现这个接口PageHelper就实现了改接口

package org.apache.ibatis.plugin;import java.util.Properties;/*** @author Clinton Begin*/
public interface Interceptor {Object intercept(Invocation invocation) throws Throwable;Object plugin(Object target);void setProperties(Properties properties);}

1:intercept 拦截器,它将直接覆盖掉你真实拦截对象的方法。

2:plugin方法它是一个生成动态代理对象的方法

3:setProperties它是允许你在使用插件的时候设置参数值。

看下com.github.pagehelper.PageHelper分页的实现了那些

    /*** Mybatis拦截器方法** @param invocation 拦截器入参* @return 返回执行结果* @throws Throwable 抛出异常*/public Object intercept(Invocation invocation) throws Throwable {if (autoRuntimeDialect) {SqlUtil sqlUtil = getSqlUtil(invocation);return sqlUtil.processPage(invocation);} else {if (autoDialect) {initSqlUtil(invocation);}return sqlUtil.processPage(invocation);}}

这个方法获取了是分页核心代码,重新构建了BoundSql对象下面会详细分析

    /*** 只拦截Executor** @param target* @return*/public Object plugin(Object target) {if (target instanceof Executor) {return Plugin.wrap(target, this);} else {return target;}}

这个方法是正对Executor进行拦截

    /*** 设置属性值** @param p 属性值*/public void setProperties(Properties p) {checkVersion();//多数据源时,获取jdbcurl后是否关闭数据源String closeConn = p.getProperty("closeConn");//解决#97if(StringUtil.isNotEmpty(closeConn)){this.closeConn = Boolean.parseBoolean(closeConn);}//初始化SqlUtil的PARAMSSqlUtil.setParams(p.getProperty("params"));//数据库方言String dialect = p.getProperty("dialect");String runtimeDialect = p.getProperty("autoRuntimeDialect");if (StringUtil.isNotEmpty(runtimeDialect) && runtimeDialect.equalsIgnoreCase("TRUE")) {this.autoRuntimeDialect = true;this.autoDialect = false;this.properties = p;} else if (StringUtil.isEmpty(dialect)) {autoDialect = true;this.properties = p;} else {autoDialect = false;sqlUtil = new SqlUtil(dialect);sqlUtil.setProperties(p);}}

基本的属性设置

二、Plugin初始化

初始化和所有mybatis的初始化一样的在之前的文章里面已经分析了 《Mybatis源码分析之SqlSessionFactory(一)》

private void pluginElement(XNode parent) throws Exception {  if (parent != null) {  for (XNode child : parent.getChildren()) {  String interceptor = child.getStringAttribute("interceptor");  Properties properties = child.getChildrenAsProperties();  Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();  interceptorInstance.setProperties(properties);  configuration.addInterceptor(interceptorInstance);  }  }
}

这里是讲多个实例化的插件对象放入configuration,addInterceptor最终存放到一个list里面的,以为这可以同时存放多个Plugin

三、Plugin拦截

插件可以拦截mybatis的4大对象ParameterHandler、ResultSetHandler、StatementHandler、Executor,源码如下图

在Configuration类里面可以找到

PageHelper使用了Executor进行拦截,上面的的源码里面已经可以看到了。

我看下上图newExecutor方法

executor = (Executor) interceptorChain.pluginAll(executor);

这个是生产一个代理对象,生产了代理对象就运行带invoke方法

四、Plugin运行

mybatis自己带了Plugin方法,源码如下

public class Plugin implements InvocationHandler {private Object target;private Interceptor interceptor;private Map<Class<?>, Set<Method>> signatureMap;private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {this.target = target;this.interceptor = interceptor;this.signatureMap = signatureMap;}public static Object wrap(Object target, Interceptor interceptor) {Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);Class<?> type = target.getClass();Class<?>[] interfaces = getAllInterfaces(type, signatureMap);if (interfaces.length > 0) {return Proxy.newProxyInstance(type.getClassLoader(),interfaces,new Plugin(target, interceptor, signatureMap));}return target;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {try {Set<Method> methods = signatureMap.get(method.getDeclaringClass());if (methods != null && methods.contains(method)) {return interceptor.intercept(new Invocation(target, method, args));}return method.invoke(target, args);} catch (Exception e) {throw ExceptionUtil.unwrapThrowable(e);}}private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);// issue #251if (interceptsAnnotation == null) {throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());      }Signature[] sigs = interceptsAnnotation.value();Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();for (Signature sig : sigs) {Set<Method> methods = signatureMap.get(sig.type());if (methods == null) {methods = new HashSet<Method>();signatureMap.put(sig.type(), methods);}try {Method method = sig.type().getMethod(sig.method(), sig.args());methods.add(method);} catch (NoSuchMethodException e) {throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);}}return signatureMap;}private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {Set<Class<?>> interfaces = new HashSet<Class<?>>();while (type != null) {for (Class<?> c : type.getInterfaces()) {if (signatureMap.containsKey(c)) {interfaces.add(c);}}type = type.getSuperclass();}return interfaces.toArray(new Class<?>[interfaces.size()]);}
}

wrap方法是为了生成一个动态代理类。

invoke方法是代理绑定的方法,该方法首先判定签名类和方法是否存在,如果不存在则直接反射调度被拦截对象的方法,如果存在则调度插件的interceptor方法,这时候会初始化一个Invocation对象

我们在具体看下PageHelper,当执行到invoke后程序将跳转到PageHelper.intercept

 public Object intercept(Invocation invocation) throws Throwable {if (autoRuntimeDialect) {SqlUtil sqlUtil = getSqlUtil(invocation);return sqlUtil.processPage(invocation);} else {if (autoDialect) {initSqlUtil(invocation);}return sqlUtil.processPage(invocation);}}

我们在来看sqlUtil.processPage方法

 /*** Mybatis拦截器方法,这一步嵌套为了在出现异常时也可以清空Threadlocal** @param invocation 拦截器入参* @return 返回执行结果* @throws Throwable 抛出异常*/public Object processPage(Invocation invocation) throws Throwable {try {Object result = _processPage(invocation);return result;} finally {clearLocalPage();}}

继续跟进

   /*** Mybatis拦截器方法** @param invocation 拦截器入参* @return 返回执行结果* @throws Throwable 抛出异常*/private Object _processPage(Invocation invocation) throws Throwable {final Object[] args = invocation.getArgs();Page page = null;//支持方法参数时,会先尝试获取Pageif (supportMethodsArguments) {page = getPage(args);}//分页信息RowBounds rowBounds = (RowBounds) args[2];//支持方法参数时,如果page == null就说明没有分页条件,不需要分页查询if ((supportMethodsArguments && page == null)//当不支持分页参数时,判断LocalPage和RowBounds判断是否需要分页|| (!supportMethodsArguments && SqlUtil.getLocalPage() == null && rowBounds == RowBounds.DEFAULT)) {return invocation.proceed();} else {//不支持分页参数时,page==null,这里需要获取if (!supportMethodsArguments && page == null) {page = getPage(args);}return doProcessPage(invocation, page, args);}}

这些都只是分装page方法,真正的核心是doProcessPage

  /*** Mybatis拦截器方法** @param invocation 拦截器入参* @return 返回执行结果* @throws Throwable 抛出异常*/private Page doProcessPage(Invocation invocation, Page page, Object[] args) throws Throwable {//保存RowBounds状态RowBounds rowBounds = (RowBounds) args[2];//获取原始的msMappedStatement ms = (MappedStatement) args[0];//判断并处理为PageSqlSourceif (!isPageSqlSource(ms)) {processMappedStatement(ms);}//设置当前的parser,后面每次使用前都会set,ThreadLocal的值不会产生不良影响((PageSqlSource)ms.getSqlSource()).setParser(parser);try {//忽略RowBounds-否则会进行Mybatis自带的内存分页args[2] = RowBounds.DEFAULT;//如果只进行排序 或 pageSizeZero的判断if (isQueryOnly(page)) {return doQueryOnly(page, invocation);}//简单的通过total的值来判断是否进行count查询if (page.isCount()) {page.setCountSignal(Boolean.TRUE);//替换MSargs[0] = msCountMap.get(ms.getId());//查询总数Object result = invocation.proceed();//还原msargs[0] = ms;//设置总数page.setTotal((Integer) ((List) result).get(0));if (page.getTotal() == 0) {return page;}} else {page.setTotal(-1l);}//pageSize>0的时候执行分页查询,pageSize<=0的时候不执行相当于可能只返回了一个countif (page.getPageSize() > 0 &&((rowBounds == RowBounds.DEFAULT && page.getPageNum() > 0)|| rowBounds != RowBounds.DEFAULT)) {//将参数中的MappedStatement替换为新的qspage.setCountSignal(null);BoundSql boundSql = ms.getBoundSql(args[1]);args[1] = parser.setPageParameter(ms, args[1], boundSql, page);page.setCountSignal(Boolean.FALSE);//执行分页查询Object result = invocation.proceed();//得到处理结果page.addAll((List) result);}} finally {((PageSqlSource)ms.getSqlSource()).removeParser();}//返回结果return page;}

上面的有两个 Object result = invocation.proceed()执行,第一个是执行统计总条数,第二个是执行执行分页的查询的数据

里面用到了代理。最终第一回返回一个总条数,第二个把分页的数据得到。

五:PageHelper使用

以上讲解了Mybatis的插件原理和PageHelper相关的内部实现,下面具体讲讲PageHelper使用

1:先增加maven依赖:

<dependency>  <groupId>com.github.pagehelper</groupId>  <artifactId>pagehelper</artifactId>  <version>4.1.6</version>
</dependency

2:配置configuration.xml文件加入如下配置(plugins应该在environments的上面 )

<plugins><!-- PageHelper4.1.6 --> <plugin interceptor="com.github.pagehelper.PageHelper"><property name="dialect" value="mysql"/><property name="offsetAsPageNum" value="false"/><property name="rowBoundsWithCount" value="false"/><property name="pageSizeZero" value="true"/><property name="reasonable" value="false"/><property name="supportMethodsArguments" value="false"/><property name="returnPageInfo" value="none"/></plugin></plugins>

相关字段说明可以查看SqlUtilConfig源码里面都用说明

注意配置的时候顺序不能乱了否则报错

Caused by: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: org.xml.sax.SAXParseException; lineNumber: 57; columnNumber: 17; 元素类型为 "configuration" 的内容必须匹配 "(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,plugins?,environments?,databaseIdProvider?,mappers?)"。
at org.apache.ibatis.parsing.XPathParser.createDocument(XPathParser.java:259)
at org.apache.ibatis.parsing.XPathParser.<init>(XPathParser.java:120)
at org.apache.ibatis.builder.xml.XMLConfigBuilder.<init>(XMLConfigBuilder.java:66)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:49)
... 2 more

意思是配置里面的节点顺序是properties->settings->typeAliases->typeHandlers->objectFactory->objectWrapperFactory->plugins->environments->databaseIdProvider->mappers   plugins应该在environments之前objectWrapperFactory之后  这个顺序不能乱了

3:具体使用

1:分页

  SqlSession sqlSession = sessionFactory.openSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);PageHelper.startPage(1,10,true);  //第一页 每页显示10条Page<User> page=userMapper.findUserAll();

2:不分页

 PageHelper.startPage(1,-1,true);

3:查询总条数

PageInfo<User>  info=new PageInfo<>(userMapper.findUserAll());

来源:http://www.ccblog.cn/92.htm
null

Mybatis插件原理和PageHelper结合实战分页插件(七)相关推荐

  1. Spring boot 实战指南(二):Mybatis、动态绑定、多数据源、分页插件、Mybatis-Plus

    文章目录 一.整合Mybatis 1.搭建数据库环境 2.基于注解整合Mybatis (1)创建项目 (2)具体代码实现 (3)测试 3.基于xml整合Mybatis 4.Mybatis的动态SQL ...

  2. limt和(pagehelper或者page分页插件)的区别

    limit mysql当中的分页SQL应该怎么写? ①使用limit关键字,语法格式:limit startIndex,pageSize ②第⼀个数字:startIndex(起始下标,下标从0开始) ...

  3. MyBatis的逆向工程、QBC查询(分页插件)

    目录 1.创建逆向工程的步骤 a>添加依赖和插件 b>创建MyBatis的核心配置文件 c>创建逆向工程的配置文件 d>执行MBG插件的generate目标 2.QBC查询 分 ...

  4. java jquery 分页插件怎样实现_jQuery实现的分页插件完整示例

    本文实例讲述了jQuery实现的分页插件.分享给大家供大家参考,具体如下: 呈现 html文件 Insert title here var pages=10; //计算出总页数(一定要是5的倍数) f ...

  5. spring boot+mybatis+thymeleaf+pagehelper分页插件实现分页功能

    文章目录 前言 正文 业务场景 后端 pom.xml application.yml 实体类video.java和User.java----映射VideoMapper.xml----VideoMapp ...

  6. 手写MyBatis分页插件

    目录 前言 MyBatis插件 手写分页插件 总结 前言 在开发查询类的接口时,有一个让开发者比较头疼的问题:分页. 如果每次都要开发者自己去写limit,计算起始行和偏移量就太烦了,于是市面上诞生了 ...

  7. 【MyBatis】MyBatis分页插件PageHelper的使用

    转载自 https://www.cnblogs.com/shanheyongmu/p/5864047.html 好多天没写博客了,因为最近在实习,大部分时间在熟悉实习相关的东西,也没有怎么学习新的东西 ...

  8. MyBatis学习总结(17)——Mybatis分页插件PageHelper

    2019独角兽企业重金招聘Python工程师标准>>> 如果你也在用Mybatis,建议尝试该分页插件,这一定是最方便使用的分页插件. 分页插件支持任何复杂的单表.多表分页,部分特殊 ...

  9. springboot2.0.5集成mybatis(PageHelper分页插件、generator插件使用)

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/zab635590867/article ...

最新文章

  1. postgresql----文本搜索类型和检索函数
  2. 关于位运算的错误问题
  3. spock 集成测试_Spock 1.2 –轻松进行集成测试中的Spring Bean模拟
  4. Shell 字符串截取
  5. appsettings 连接oracle数据库,ABP .net core集成访问Oracle数据库
  6. Centos 7 安装 memcached
  7. TabBar与下拉列表访问数据与刷新
  8. 大数据开发笔记(四):Hive数仓调优
  9. 工程师应用计算机考试题型,IE工程师考试试题
  10. 所以,FileWriter和BufferedWriter的真正区别在哪
  11. 592. Fraction Addition and Subtraction
  12. 小白学java-JVM知识点总结
  13. LCP 3. 机器人大冒险
  14. mysql config.xml_generatorConfig-mysql.xml中连接数据库的正确书写方式。
  15. mysql和pg数据库表备份及还原
  16. 如何实现罗克韦尔PLC的模拟量采集和远程上下载?
  17. 关于解决移动端息屏后定时器不工作的问题
  18. 人工智能中的顶级期刊
  19. 工程行业数字化采购商城平台提供科学采购决策,提高采购管理水平
  20. A Double-Stage Kalman Filter for Orientation Tracking With An Integrated Processor in 9-D IMU

热门文章

  1. C++实现十大排序算法(冒泡,选择,插入,归并,快速,堆,希尔,桶,计数,基数)排序算法时间复杂度、空间复杂度、稳定性比较(面试经验总结)
  2. ASP.NET抓取其他网页代码
  3. 虚拟主机上用Asp.net实现Urlrewrite
  4. 【C++】C++11 STL算法(五):设置操作(Set operations)、堆操作(Heap operations)
  5. 【C++】google gflags详解
  6. 【OpenCV】cv::VideoCapture 多线程测试
  7. linux驱动:TI+DM8127+GPIO(二)之驱动
  8. 分享一个ssh打通的脚本
  9. birt报表表格边框_手把手教你五步制作出一张领导驾驶舱报表
  10. linux 雷电接口,Intel完全开放雷电技术:底层融合USB 4