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 { @Autowired
private List<SqlSessionFactory> sqlSessionFactoryList; @Autowired
private PageHelperProperties properties;//配置文件 /**
* 接受分页插件额外的属性
*
* @return
*/
@Bean
@ConfigurationProperties(prefix = PageHelperProperties.PAGEHELPER_PREFIX)//将配置文件实例化为properties
public 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查询的ms
protected 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拦截方法,当拦截到相应的方法后,后走该改法判断时候需要改变

@Override
public 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 类型的 ms
countMs = 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)) {
//生成分页的缓存 key
CacheKey pageKey = cacheKey;
//处理参数对象
parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey);
//调用方言获取分页 sql
String 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中是否已经有了page
if (oldPage != null && oldPage.isOrderByOnly()) {
page.setOrderBy(oldPage.getOrderBy());
}
setLocalPage(page);
return page;
}

springboot中的mybatis是如果使用pagehelper的的更多相关文章

  1. springboot中使用mybatis的分页插件pageHelper

    首先在pom.xml中配置 <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot ...

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

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

  3. springboot中使用mybatis显示执行sql

    springboot 中使用mybatis显示执行sql的配置,在properties中添加如下 logging.你的包名=debug 2018-11-27 16:35:43.044 [DubboSe ...

  4. 在springboot中集成mybatis开发

    在springboot中利用mybatis框架进行开发需要集成mybatis才能进行开发,那么如何在springboot中集成mybatis呢?按照以下几个步骤就可以实现springboot集成myb ...

  5. 在springboot中使用Mybatis Generator的两种方式

    介绍 Mybatis Generator(MBG)是Mybatis的一个代码生成工具.MBG解决了对数据库操作有最大影响的一些CRUD操作,很大程度上提升开发效率.如果需要联合查询仍然需要手写sql. ...

  6. springboot中使用mybatis之mapper

    Spring Boot中使用MyBatis传参方式:使用@Param@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})& ...

  7. SpringBoot 中 使用Mybatis时 如果后端数据库为 Oracle注意事项

    报错信息如下: Could not set parameters for mapping: ParameterMapping{property='age', mode=IN, javaType=cla ...

  8. spring-boot+mybatis开发实战:如何在spring-boot中使用myabtis持久层框架

    前言: 本项目基于maven构建,使用mybatis-spring-boot作为spring-boot项目的持久层框架 spring-boot中使用mybatis持久层框架与原spring项目使用方式 ...

  9. SpringBoot添加对Mybatis的支持

    1.修改maven配置文件pom.xml,添加对mybatis的支持: <dependency> <groupId>org.mybatis.spring.boot</gr ...

随机推荐

  1. Logstash配置文件详情

    logstash 配置文件编写详解 说明 它一个有jruby语言编写的运行在java虚拟机上的具有收集分析转发数据流功能的工具能集中处理各种类型的数据能标准化不通模式和格式的数据能快速的扩展自定义日志 ...

  2. 简述IOC和AOP的作用

    IOC: 控制反转,是一种设计模式.一层含义是控制权的转移:由传统的在程序中控制依赖转移到由容器来控制:第二层是依赖注入:将相互依赖的对象分离,在spring配置文件中描述他们的依赖关系.他们的依赖关 ...

  3. β版本apk下载地址及源代码github地址

    β版本下载地址   源代码下载地址:https://github.com/U-Help/Version-1.0 安装包下载地址:百度网盘:(密码q3sy)https://pan.baidu.com/s ...

  4. Nginx的应用之虚拟主机

    开始前请确保selinux关闭,否则当配置完虚拟主机后,尽管权限或者网站目录都正确,访问的结果也是403 nginx的虚拟主机有三种方式: 一.基于域名的虚拟主机 (1)创建对应的web站点目录以及程 ...

  5. 在脚本中使用set命令调试脚本

    当脚本文件较长时,可以使用set命令指定调试一段脚本.在脚本中使用set -x命令开启调式模式:使用set +x命令关闭调式模式. 例如: #!/bin/bash #Scriptname: greet ...

  6. numpy.unique

    Find the unique elements of an array. Returns the sorted unique elements of an array. There are thre ...

  7. 【Flutter学习】之Widget数据共享之InheritedWidget

    一,概述 业务开发中经常会碰到这样的情况,多个Widget需要同步同一份全局数据,比如点赞数.评论数.夜间模式等等.在安卓中,一般的实现方式是观察者模式,需要开发者自行实现并维护观察者的列表.在flu ...

  8. Android中的ImageView的getDrawableCache获取背景图片的时候注意的问题

    获取ImageView的背景图片使用getDrawableCache方法,不要使用getDrawable方法,后者获取不到图片的. 1.在调用imageView.getDrawableCache()之 ...

  9. 【MySQL】mysql查询强制大小写及替换字段

    强制大小写 select * from test where name like BINARY '%Adc%' mysql替换字段 update test set name= REPLACE (nam ...

  10. Cisco基础(六):配置目前网络环境、项目阶段练习

    一.配置目前网络环境 目标: 一家新创建的IT公司,公司位于北京有80多台服务器 目前网络环境使用技术,通过端口映射技术将web服务器发布给Internet: 三层交换:汇聚接入层交换机 默认路由:实 ...