当前位置: 首页 > 编程日记 > 正文

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

今天和大家分享下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类里面可以找到

1040703-20170114230319791-2091894689.png

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


相关文章:

直方图反向投影

#include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <iostream> using namespace cv; using namespace std; int main() {// 加载源图像并验证cv::Mat srcImage cv::imread("..\\images\\hand1.jpg&quo…

Java异常处理12条军规

摘要&#xff1a; 简单实用的建议。 原文&#xff1a;Java异常处理12条军规公众号&#xff1a;Spring源码解析Fundebug经授权转载&#xff0c;版权归原作者所有。 在Java语言中&#xff0c;异常从使用方式上可以分为两大类&#xff1a; CheckedExceptionUncheckedException在Ja…

【Smart_Point】C/C++ 中独占指针unique_ptr

1. 独占指针unique_ptr 目录 1. 独占指针unique_ptr 1.1 unique_ptr含义 1.2 C11特性 1.3 C14特性 1.1 unique_ptr含义 unique_ptr 是 C 11 提供的用于防止内存泄漏的智能指针中的一种实现&#xff0c;独享被管理对象指针所有权的智能指针。unique_ptr对象包装一个原始指…

ORA-01940无法删除当前已连接用户

原文地址&#xff1a;ORA-01940无法删除当前已连接用户作者&#xff1a;17361887941)查看用户的连接状况 select username,sid,serial# from v$session ------------------------------------------ 如下结果&#xff1a; username sid serial# ------…

距离变换扫描实现

#include <opencv2/imgproc/imgproc.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> // 计算欧式距离 float calcEuclideanDistance(int x1, int y1, int x2, int y2) {return sqrt(…

『扩欧简单运用』

扩展欧几里得算法 顾名思义&#xff0c;扩欧就是扩展欧几里得算法&#xff0c;那么我们先来简单地回顾一下这个经典数论算法。 对于形如\(axbyc\)的不定方程&#xff0c;扩展欧几里得算法可以在\(O(log_2alog_2b)\)的时间内找到该方程的一组特解&#xff0c;或辅助\(gcd\)判断该…

【Smart_Point】C/C++ 中共享指针 shared_ptr

1. 共享指针 shared_ptr 目录 1. 共享指针 shared_ptr 1.1 共享指针解决的问题&#xff1f; 1.2 创建 shared_ptr 对象 1.3 分离关联的原始指针 1.4 自定义删除器 Deleter 1.5 shared_ptr 相对于普通指针的优缺点 1.6 创建 shared_ptr 时注意事项 1.1 共享指针解决的问…

对数变换的三种实现方法

#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> using namespace cv; // 对数变换方法1 cv::Mat logTransform1(cv::Mat srcImage, int c) {// 输…

eclipse编辑窗口不见了(打开左边的java、xml文件,中间不会显示代码)

转自&#xff1a;https://blog.csdn.net/u012062810/article/details/46729779?utm_sourceblogxgwz4 1. windows-->reset Perspective 窗口-->重置窗口布局 2. windows -> new windows 新窗口 当时手贱了一下&#xff0c;结果…

js的执行机制

javascript的运行机制一直困扰在我&#xff0c;对其的运行机制也是一知半解&#xff0c;在看了https://juejin.im/post/59e85eebf265da430d571f89#heading-10这篇文章后&#xff0c;有种茅塞顿开的感觉,下面是原文内容&#xff1a; 认识javascript javascript是一门单线程语言&…

【Smart_Point】unique_ptr中独占指针使用MakeFrame

1. DFrame使用方法 std::unique_ptr<deptrum::Frame> MakeFrame(deptrum::FrameType frame_type,int width,int height,int bytes_per_pixel,void* data,uint64_t timestamp,int index,float temperature) {std::unique_ptr<deptrum::Frame> frame{std::make_uniq…

最大熵阈值分割

#include <opencv2/imgproc/imgproc.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> using namespace std; using namespace cv; // 计算当前的位置的能量熵 float caculateCurrentE…

php登录注册

php 登录注册 注册代码&#xff1a;register.php <style type"text/css">form{width:300px;background-color:#EEE0E5;margin-left:300px;margin-top:30px;padding:30px;}button{margin-top:20px;} </style> <form method"post"> <la…

【C++】C/C++ 中的单例模式

目录 part 0&#xff1a;单例模式3种经典的实现方式 Meyers Singleton Meyers Singleton版本二 Lazy Singleton Eager Singleton Testing part 1&#xff1a;C之单例模式 动机 实现一[线程不安全版本] 实现二[线程安全&#xff0c;锁的代价过高] 锁机制 实现三[双检…

计算图像波峰点

#include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <stdio.h> #include <iostream> #include <vector> using namespace std; using namespace cv; // 计算图像的波峰…

锁的算法,隔离级别的问题

锁的算法 InnoDB存储引擎有3中行锁的算法设计&#xff0c;分别是&#xff1a; Record Lock&#xff1a;单个行记录上的锁。Gap Lock&#xff1a;间隙锁&#xff0c;锁定一个范围&#xff0c;但不包含记录本身。Next-Key Lock&#xff1a;Gap LockRecord Lock&#xff0c;锁定一…

好程序员分享24个canvas基础知识小结

好程序员分享24个canvas基础知识小结&#xff0c;非常全面详尽&#xff0c;推荐给大家。 现把canvas的知识点总结如下&#xff0c;以便随时查阅。 1、填充矩形 fillRect(x,y,width,height); 2、绘制矩形边框 strokeRect(x,y,width,height); 3、擦除矩形 clearRect(x,y,width,he…

【leetcode】二叉树与经典问题

文章目录笔记leetcode [114. 二叉树展开为链表](https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/)解法一: 后序遍历、递归leetcode [226. 翻转二叉树](https://leetcode-cn.com/problems/invert-binary-tree/)思路与算法复杂度分析leetcode [剑指 Offer…

PHP PSR-1 基本代码规范(中文版)

基本代码规范 本篇规范制定了代码基本元素的相关标准&#xff0c;以确保共享的PHP代码间具有较高程度的技术互通性。 关键词 “必须”("MUST")、“一定不可/一定不能”("MUST NOT")、“需要”("REQUIRED")、“将会”("SHALL")、“不会…

最近邻插值实现:图像任意尺寸变换

#<opencv2/imgproc/imgproc.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> using namespace cv; using namespace std; // 实现最近邻插值图像缩放 cv::Mat nNeighbourInterpolatio…

软件测试-培训的套路-log3

最新的套路&#xff01;我是没了解过--下图中描述-log3 Dotest-董浩 但是我知道不管什么没有白吃的午餐而且还会给钱…如果真的有&#xff0c;请醒醒&#xff01; 当然话又回来&#xff0c;套路不套路&#xff0c;关键看你是否需要&#xff1b;你如果需要我觉得是帮你…不需要&…

ALSA声卡驱动中的DAPM详解之四:在驱动程序中初始化并注册widget和route

前几篇文章我们从dapm的数据结构入手&#xff0c;了解了代表音频控件的widget&#xff0c;代表连接路径的route以及用于连接两个widget的path。之前都是一些概念的讲解以及对数据结构中各个字段的说明&#xff0c;从本章开始&#xff0c;我们要从代码入手&#xff0c;分析dapm的…

双线性插值实现

#include <opencv2/imgproc/imgproc.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> // 实现双线性插值图像缩放 cv::Mat BilinearInterpolation(cv::Mat srcImage) {CV_Assert(srcI…

【C++】C++ 强制转换运算符

C 运算符 强制转换运算符是一种特殊的运算符&#xff0c;它把一种数据类型转换为另一种数据类型。强制转换运算符是一元运算符&#xff0c;它的优先级与其他一元运算符相同。 大多数的 C 编译器都支持大部分通用的强制转换运算符&#xff1a; (type) expression 其中&…

WPS 2019 更新版(8392)发布,搭配优麒麟 19.04 运行更奇妙!

WPS 2019 支持全新的外观界面、目录更新、方框打勾、智能填充、内置浏览器、窗口拆组、个人中心等功能。特别是全新的新建页面&#xff0c;让你可以整合最近打开的文档、本地模版、公文模版、在线模板等。 随着优麒麟即将发布的新版 19.04 的到来&#xff0c;金山办公软件也带来…

图像金字塔操作,上采样、下采样、缩放

#include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <iostream> // 图像金子塔采样操作 void Pyramid(cv::Mat srcImage) {// 根据图像源尺寸判断是否需要缩放if(srcImage.rows > 400 && srcImage…

【C++】【OpenCv】图片加噪声处理,计时,及键盘事件响应捕捉

图像噪声添加 cv::Mat addGuassianNoise(cv::Mat& src, double a, double b) {cv::Mat temp src.clone();cv::Mat dst(src.size(), src.type()); ​// Construct a matrix containing Gaussian noisecv::Mat noise(temp.size(), temp.type());cv::RNG rng(time(NULL));//…

透视学理论(十四)

2019独角兽企业重金招聘Python工程师标准>>> 已知左右距点分别位于透视画面两侧&#xff0c;因此我们可以左距点来得出透视画面的纵深长度。 距点&#xff0c;指的是与透视画面成45的水平线的消失点。我们把画面边缘按1米的宽度&#xff08;A点&#xff09;&#xf…

适用于Mac上的SQL Server

适用于Mac上的SQL Server&#xff1f; 众所周知&#xff0c;很多人都在电脑上安装了SQL Server软件&#xff0c;普通用户直接去官网下载安装即可&#xff0c;Mac用户则该如何在Mac电脑上安装SQL Server呢&#xff1f;想要一款适用于Mac上的SQL Server&#xff1f;点击进入&…

【MATLAB】————拷贝指定文件路径下的有序文件(选择后),可处理固定规律的文件图片数据或者文件

总体上来说这种数据有2中处理思路。第一种如下所示&#xff0c;从一组数据中挑选出符合要求的数据&#xff1b; 第二中就是数据中不需要的数据删除&#xff0c;选择处理不需要的数据&#xff0c;留下的补集就是需要的数库。一般情况下需要看问题是否明确&#xff0c;需求明确的…