springboot中的mybatis是如果使用pagehelper的

springboot中使用其他组件都是基于自动配置的AutoConfiguration配置累的,pagehelper插件也是一样的,通过PageHelperAutoConfiguration的,这个类存在于jar包的spring.factories

文件中,当springboot启动时会通过selector自动将配置类加载到上下文中

springboot集成pagehelper,pom依赖:

        <dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.0</version></dependency><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.1.2</version></dependency><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-autoconfigure</artifactId>   ---作用自动配置pagehelper<version>1.2.3</version></dependency>

关键类:

PageHelperAutoConfiguration.java

package com.github.pagehelper.autoconfigure;import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Properties;/*** 自定注入分页插件** @author liuzh*/
@Configuration //表明当前了是一个配置类
@ConditionalOnBean(SqlSessionFactory.class)//当有SqlSesionFactory这个类的时候才实例化当前类
@EnableConfigurationProperties(PageHelperProperties.class)//pagehelpser的配置文件
@AutoConfigureAfter(MybatisAutoConfiguration.class)//当前类是在mybatisAutoconfiguration配置类初始化之后才初始化
public class PageHelperAutoConfiguration {@Autowiredprivate List<SqlSessionFactory> sqlSessionFactoryList;@Autowiredprivate PageHelperProperties properties;//配置文件/*** 接受分页插件额外的属性** @return*/@Bean@ConfigurationProperties(prefix = PageHelperProperties.PAGEHELPER_PREFIX)//将配置文件实例化为propertiespublic Properties pageHelperProperties() {return new Properties();}@PostConstruct//实例化之后条用当前方法,将pagehelper插件添加到myabtis的核心配置文件中(Configuration中) PageInterceptor就是pagehelper的插件public void addPageInterceptor() {PageInterceptor interceptor = new PageInterceptor();Properties properties = new Properties();//先把一般方式配置的属性放进去properties.putAll(pageHelperProperties());//在把特殊配置放进去,由于close-conn 利用上面方式时,属性名就是 close-conn 而不是 closeConn,所以需要额外的一步properties.putAll(this.properties.getProperties());interceptor.setProperties(properties);for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {sqlSessionFactory.getConfiguration().addInterceptor(interceptor);}}}

进一步看PageInterceptor.java,这个类就是mybatis的插件,先看类上的注解,@Interceptos注解表名当前类是一个拦截器,里边会有@Signature注解,这个注解主要配置的就是拦截的方法,如type:拦截的类是Executor,method:拦截的方法,args:拦截方法

的参数

@Intercepts(//这个注解是mybatis中的注解{@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 {//缓存count查询的msprotected Cache<String, MappedStatement> msCountMap = null;private Dialect dialect;//这个是pagehelper的一个接口,里边有数据库的一些方言配置private String default_dialect_class = "com.github.pagehelper.PageHelper";//默认的方言实现类,如果上边那个dialect没有配置的话,默认走这个private Field additionalParametersField;private String countSuffix = "_COUNT";

Dialect的一些实现类,不同的数据库使用不同的实现类,其中,pagehelper是默认的方言(这个类是在没有配置其他方言的时候,默认实例化的)

PageInterceptor类中的关键方法:intercept拦截方法,当拦截到相应的方法后,后走该改法判断时候需要改变

@Overridepublic Object intercept(Invocation invocation) throws Throwable {try {Object[] args = invocation.getArgs();//获取拦截到的方法的所有参数 下边获取0,1,2,3是进行强制转换对应的类,这个是根据@intercepts注解中的@sisignature中的args得到的MappedStatement ms = (MappedStatement) args[0];Object parameter = args[1];RowBounds rowBounds = (RowBounds) args[2];ResultHandler resultHandler = (ResultHandler) args[3];Executor executor = (Executor) invocation.getTarget();CacheKey cacheKey;BoundSql boundSql;//由于逻辑关系,只会进入一次  分两种情况4个参数和6个参数也是根据注解@signature的args类判断的if(args.length == 4){//4 个参数时boundSql = ms.getBoundSql(parameter);cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);} else {//6 个参数时cacheKey = (CacheKey) args[4];boundSql = (BoundSql) args[5];}List resultList;//调用方法判断是否需要进行分页,如果不需要,直接返回结果  例如dialect使用的是默认的实现类的话,判断是否要跳过分页,是根据代码中查询数据库是,是否执行过PageHelper.startPage()方法类判断的(一种情况),执行过,则要分页,否则不分页if (!dialect.skip(ms, parameter, rowBounds)) {//反射获取动态参数String msId = ms.getId();Configuration configuration = ms.getConfiguration();Map<String, Object> additionalParameters = (Map<String, Object>) additionalParametersField.get(boundSql);//下边会进行两步:1、总数查询 2、分页查询//判断是否需要进行 count 查询if (dialect.beforeCount(ms, parameter, rowBounds)) {String countMsId = msId + countSuffix;Long count;//先判断是否存在手写的 count 查询MappedStatement countMs = getExistedMappedStatement(configuration, countMsId);if(countMs != null){count = executeManualCount(executor, countMs, parameter, boundSql, resultHandler);} else {countMs = msCountMap.get(countMsId);//自动创建if (countMs == null) {//根据当前的 ms 创建一个返回值为 Long 类型的 mscountMs = MSUtils.newCountMappedStatement(ms, countMsId);msCountMap.put(countMsId, countMs);}count = executeAutoCount(executor, countMs, parameter, boundSql, rowBounds, resultHandler);}//处理查询总数//返回 true 时继续分页查询,false 时直接返回if (!dialect.afterCount(count, parameter, rowBounds)) {//当查询总数为 0 时,直接返回空的结果return dialect.afterPage(new ArrayList(), parameter, rowBounds);}}//判断是否需要进行分页查询if (dialect.beforePage(ms, parameter, rowBounds)) {//生成分页的缓存 keyCacheKey pageKey = cacheKey;//处理参数对象parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey);//调用方言获取分页 sqlString pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey);BoundSql pageBoundSql = new BoundSql(configuration, pageSql, boundSql.getParameterMappings(), parameter);//设置动态参数for (String key : additionalParameters.keySet()) {pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key));}//执行分页查询resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql);} else {//不执行分页的情况下,也不执行内存分页resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql);}} else {//rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);}return dialect.afterPage(resultList, parameter, rowBounds);} finally {dialect.afterAll();}}

例子:

        Page<TUser> startPage = PageHelper.startPage(1, 2);List<TUser> list1 = mapper.selectByEmailAndSex1(params);

//在查询数据库之前先执行startPage方法,传入分页参数进入starepage方法(这个方法在pagehelper的父类pagemethod中),startPage方法有多个重载的方法,该例子中用的是两个参数的

 /*** 开始分页** @param pageNum  页码* @param pageSize 每页显示数量*/public static <E> Page<E> startPage(int pageNum, int pageSize) {return startPage(pageNum, pageSize, true);}

   /*** 开始分页** @param pageNum  页码* @param pageSize 每页显示数量* @param count    是否进行count查询*/public static <E> Page<E> startPage(int pageNum, int pageSize, boolean count) {return startPage(pageNum, pageSize, count, null, null);}

   /*** 开始分页** @param pageNum      页码* @param pageSize     每页显示数量* @param count        是否进行count查询* @param reasonable   分页合理化,null时用默认配置* @param pageSizeZero true且pageSize=0时返回全部结果,false时分页,null时用默认配置*/public static <E> Page<E> startPage(int pageNum, int pageSize, boolean count, Boolean reasonable, Boolean pageSizeZero) {Page<E> page = new Page<E>(pageNum, pageSize, count);page.setReasonable(reasonable);page.setPageSizeZero(pageSizeZero);//当已经执行过orderBy的时候Page<E> oldPage = getLocalPage();//查询ThreadLocal中是否已经有了pageif (oldPage != null && oldPage.isOrderByOnly()) {page.setOrderBy(oldPage.getOrderBy());}setLocalPage(page);return page;}

posted @ 2019-05-28 22:40 巡山小妖N 阅读(...) 评论(...) 编辑 收藏

springboot中的mybatis是如果使用pagehelper的相关推荐

  1. SpringBoot中关于Mybatis使用的三个问题

    SpringBoot中关于Mybatis使用的三个问题 转载请注明源地址:http://www.cnblogs.com/funnyzpc/p/8495453.html 原本是要讲讲PostgreSQL ...

  2. springboot中整合mybatis及简单使用

    springboot中整合mybatis及简单使用 1.引入依赖 2.在applicaiton.yaml中配置数据源以及mybatis 3.创建sql测试表 4.编写mapper接口和mapper.x ...

  3. SpringBoot中使用mybatis/ibatis日志打印sql

    SpringBoot中使用mybatis/ibatis时日志打印sql 控制台打印mybatis/ibatis对应的sql 主机的日志文件中打印mybatis/ibatis对应的sql 控制台打印my ...

  4. 在springboot中使用mybatis generate自动生成实体类和mapper

    1.在全局的pom中引入mybatis generate的依赖 <!--自动生成实体--><dependency><groupId>org.mybatis.gene ...

  5. SpringBoot中关闭Mybatis以及RocketMQ日志打印

    SpringBoot工程集成了Mybatis和RocketMQ,也集成了Log4j,项目中自己的日志都可以通过log4j来管理,日志打印通过通过日志级别可以管理,一直很正常. 后来项目上线正常稳定运行 ...

  6. springboot 中使用 Mybatis 注解 配置 详解

    前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家.点击跳转到教程. 传参方式 使用不同的传参方式: 使用@Param 之前博文中的项目使用了这种简单的传参方式: @In ...

  7. SpringBoot中使用Mybatis碰到的问题记录

    每次使用Mybatis的时候都是去网上百度一下,然后照着网上的文章一步一步在自己的IDEA中进行配置,但是有时候明明是按着人家跑起来的流程配置的,但是就是不知道啥原因,有时就跑的起来,有时又不行!现在 ...

  8. Springboot中使用Mybatis框架对数据库进行联表查询,踩坑填坑

    因为mybatis使用的基本是原生sql语句 所以首先从数据库开始说 以mysql数据库为例,对表的连接查询分为四种 内连接,外连接,交叉连接,和联合连接 内连接使用比较运算符根据每个表共有的列的值匹 ...

  9. SpringBoot中使用Mybatis逆向工程(实体类含数据库注释)

    Mybatis逆向工程:根据创建好的数据库表,生成对应的实体类.DAO.映射文件 文章目录 开发环境 1.新建SpringBoot应用 2.添加逆向工程插件依赖 3.执行逆向生成 开发环境 开发工具: ...

最新文章

  1. 判断是否过期的算法_铁观音多久过期,怎么判断铁观音是否过期?
  2. 【Lv1-Lesson002】He and She
  3. excel表中判断A列与B列内容是否相同,相同的话在C列按条件输出!
  4. 数据库选项--ALTER DATABASE WITH 选项
  5. matlab disteclud,机器学习实战ByMatlab(四)二分K-means算法
  6. leetcode 第 216 场周赛 整理
  7. python怎么安装myqr_python二维码操作:对QRCode和MyQR入门详解
  8. python将十进制转为二进制_如何用Python将十进制数字转为二进制,以及将二进制转为十六进制?...
  9. Latex 导数相关符号
  10. Matplotlib安装感想
  11. 如何利用Pre.im分发iOS测试包
  12. 如何给企业选择一款ERP系统
  13. c++中两个头文件定义同名类的解决办法
  14. 最新语言表示方法XLNet
  15. git cherry-pick的使用
  16. FineReport 创建报表模板
  17. 新手亲自踩坑!Jmter使用CSV Data Set Config配置原件测试登录接口,察看结果树无响应问题
  18. Discuz中常用数据库操作
  19. 概述SAP云平台上的ABAP开发环境
  20. Temu跨境电商,自养国外买家账号补单?快速出单,掌握流量密码

热门文章

  1. mysql5.6数据库位置_MYSQL5.6数据库存放位置
  2. 前端须知的 Cookie 知识小结
  3. PHP中$_SERVER的详细参数
  4. 涉密计算机格式化维修,涉密计算机的涉密信息被删除或格式化后,通过一定的技术手段仍可以复原,连接互联网易造成泄密。()...
  5. jsoup 获取html中body内容_python爬虫之下载盗墓笔记(bs4解析HTML)
  6. element vue 获取select 的label_Vue动态组件component的深度使用
  7. nginx rewrite
  8. 【微信小程序】报错信息合集
  9. MySQL 查看执行计划
  10. uniapp H5页面使用uni.request时,出现跨域问题