写作时间:2019-09-10
Spring Boot: 2.1 ,JDK: 1.8, IDE: IntelliJ IDEA

说明

MyBatis PageHelper (https://pagehelper.github.io)

  • 支持多种数据库
  • 支持多种分页方式
  • SpringBoot 支持 (https://github.com/pagehelper/pagehelper-spring-boot)
    • pagehelper-spring-boot-starter

一般选择用下面4中写法

//第一种,RowBounds方式的调用
List<Country> list = sqlSession.selectList("x.y.selectIf", null, new RowBounds(0, 10));//第二种,Mapper接口方式的调用,推荐这种使用方式。
PageHelper.startPage(1, 10);
List<Country> list = countryMapper.selectIf(1);//第三种,Mapper接口方式的调用,推荐这种使用方式。
PageHelper.offsetPage(1, 10);
List<Country> list = countryMapper.selectIf(1);//第四种,参数方法调用
//存在以下 Mapper 接口方法,你不需要在 xml 处理后两个参数
public interface CountryMapper {List<Country> selectByPageNumSize(@Param("user") User user,@Param("pageNum") int pageNum,@Param("pageSize") int pageSize);
}
//配置supportMethodsArguments=true
//在代码中直接调用:
List<Country> list = countryMapper.selectByPageNumSize(user, 1, 10);

工程建立

参照教程【SpringBoot 2.1 | 第一篇:构建第一个SpringBoot工程】新建一个Spring Boot项目,名字叫demodbmybatisgenerator, 在目录src/main/java/resources 下找到配置文件application.properties,重命名为application.yml

在Dependency中选择
Developer Tools > Lombok
Web > Spring Web Starter
SQL > H2 DataBase / Mybatis Framework
Ops > Spring Boot Actuator。


pom.xml 修改mybatis的版本, 增加mybatis.pagehelper, joda


<dependencies><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version></dependency><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.2.10</version></dependency><dependency><groupId>org.joda</groupId><artifactId>joda-money</artifactId><version>LATEST</version></dependency>
</dependencies>

Money类型转换类

zgpeace.spring.data.handler.MoneyTypeHandler

package zgpeace.spring.data.handler;import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;/*** exchange data type between Money and BigInt for 'CNY'*/
public class MoneyTypeHandler extends BaseTypeHandler<Money> {@Overridepublic void setNonNullParameter(PreparedStatement ps, int i, Money parameter, JdbcType jdbcType) throws SQLException {ps.setLong(i, parameter.getAmountMinorLong());}@Overridepublic Money getNullableResult(ResultSet rs, String columnName) throws SQLException {return parseMoney(rs.getLong(columnName));}@Overridepublic Money getNullableResult(ResultSet rs, int columnIndex) throws SQLException {return parseMoney(rs.getLong(columnIndex));}@Overridepublic Money getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {return parseMoney(cs.getLong(columnIndex));}private Money parseMoney(Long value) {return Money.of(CurrencyUnit.of("CNY"), value / 100.0);}
}

application配置

src > main > resources > application.yml

mybatis:type-handlers-package: zgpeace.spring.data.handlerconfiguration:map-underscore-to-camel-case: true
pagehelper:offset-as-page-num: truereasonable: truepage-size-zero: truesupport-methods-arguments: true

创建表sql

Resources.schema.sql

create table t_coffee (id bigint not null auto_increment,name varchar(255),price bigint not null,create_time timestamp,update_time timestamp,primary key (id)
);

初始化数据

Resources.data.sql

insert into t_coffee (name, price, create_time, update_time) values ('espresso', 2000, now(), now());
insert into t_coffee (name, price, create_time, update_time) values ('latte', 2500, now(), now());
insert into t_coffee (name, price, create_time, update_time) values ('capuccino', 2500, now(), now());
insert into t_coffee (name, price, create_time, update_time) values ('mocha', 3000, now(), now());
insert into t_coffee (name, price, create_time, update_time) values ('macchiato', 3000, now(), now());

Model

zgpeace.spring.data.model.Coffee

package zgpeace.spring.data.model;import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.joda.money.Money;import java.util.Date;@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Coffee {private Long id;private String name;private Money price;private Date createTime;private Date updateTime;
}

Mapper

zgpeace.spring.data.mapper.CoffeeMapper

package zgpeace.spring.data.mapper;import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.session.RowBounds;
import zgpeace.spring.data.model.Coffee;import java.util.List;@Mapper
public interface CoffeeMapper {@Select("select * from t_coffee order by id")List<Coffee> findAllWithRowBounds(RowBounds rowBounds);@Select("select * from t_coffee order by id")List<Coffee> findAllWithParam(@Param("pageNum") int pageNum,@Param("pageSize") int pageSize);
}

Controller 验证分页是否可用

zgpeace.spring.data.DemoDbMybatisPageHelperApplication

package zgpeace.spring.data;import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import zgpeace.spring.data.mapper.CoffeeMapper;
import zgpeace.spring.data.model.Coffee;import java.util.List;@SpringBootApplication
@Slf4j
@MapperScan("zgpeace.spring.data.mapper")
public class DemoDbMybatisPageHelperApplication implements ApplicationRunner {@Autowiredprivate CoffeeMapper coffeeMapper;public static void main(String[] args) {SpringApplication.run(DemoDbMybatisPageHelperApplication.class, args);}@Overridepublic void run(ApplicationArguments args) throws Exception {coffeeMapper.findAllWithRowBounds(new RowBounds(1, 3)).forEach(c -> log.info("Page(1) Coffee {}", c));coffeeMapper.findAllWithRowBounds(new RowBounds(2, 3)).forEach(c -> log.info("Page(2) Coffee {}", c));log.info("===================");coffeeMapper.findAllWithRowBounds(new RowBounds(1, 0)).forEach(c -> log.info("Page(1) Coffee {}", c));log.info("===================");coffeeMapper.findAllWithParam(1, 3).forEach(c -> log.info("Page(1) Coffee {}", c));List<Coffee> list = coffeeMapper.findAllWithParam(2, 3);PageInfo page = new PageInfo(list);log.info("PageInfo: {}", page);}
}

运行数据入库和查询日志如下:

Page(1) Coffee Coffee(id=1, name=espresso, price=CNY 20.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(1) Coffee Coffee(id=2, name=latte, price=CNY 25.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(1) Coffee Coffee(id=3, name=capuccino, price=CNY 25.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(2) Coffee Coffee(id=4, name=mocha, price=CNY 30.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(2) Coffee Coffee(id=5, name=macchiato, price=CNY 30.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
===================
Page(1) Coffee Coffee(id=1, name=espresso, price=CNY 20.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(1) Coffee Coffee(id=2, name=latte, price=CNY 25.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(1) Coffee Coffee(id=3, name=capuccino, price=CNY 25.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(1) Coffee Coffee(id=4, name=mocha, price=CNY 30.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(1) Coffee Coffee(id=5, name=macchiato, price=CNY 30.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
===================
Page(1) Coffee Coffee(id=1, name=espresso, price=CNY 20.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(1) Coffee Coffee(id=2, name=latte, price=CNY 25.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(1) Coffee Coffee(id=3, name=capuccino, price=CNY 25.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)PageInfo: PageInfo{pageNum=2, pageSize=3, size=2, startRow=4, endRow=5, total=5, pages=2, list=Page{count=true, pageNum=2, pageSize=3, startRow=3, endRow=6, total=5, pages=2, reasonable=true, pageSizeZero=true}
[Coffee(id=4, name=mocha, price=CNY 30.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019),
Coffee(id=5, name=macchiato, price=CNY 30.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)], prePage=1, nextPage=0, isFirstPage=false, isLastPage=true, hasPreviousPage=true, hasNextPage=false, navigatePages=8, navigateFirstPage=1, navigateLastPage=2, navigatepageNums=[1, 2]}

总结

恭喜你,学会了Mybatis分页工具PageHelper的应用
代码下载:

https://github.com/zgpeace/Spring-Boot2.1/tree/master/db/DemoDBMybatisPageHelper

参考

https://github.com/pagehelper/Mybatis-PageHelper
https://pagehelper.github.io/docs/howtouse/
https://pagehelper.github.io/
https://github.com/pagehelper/pagehelper-spring-boot

https://github.com/geektime-geekbang/geektime-spring-family/tree/master/Chapter%203/mybatis-generator-demo

易筋SpringBoot 2.1 | 第廿二篇:SpringBoot的Mybatis分页插件PageHelper相关推荐

  1. springboot+mybatis分页插件pageHelper的配置与使用

    1.在pom文件里面加入pageHelper分页jar包依赖: <dependency><groupId>com.github.pagehelper</groupId&g ...

  2. springboot进阶,分页插件 pageHelper,Swagger整合,日志

    文章目录 1,课程回顾 2,本章重点 3,具体内容 3.1 整合连接池 3.2 springboot日志配置: 3.3 springboot整合shiro 3.4 mybatis分页插件 pageHe ...

  3. springboot整合mybatis分页插件

    1.springboot版本为2.0.1,数据库为mysql,引入pagehelper的pom依赖 <!--mybatis分页插件--> <dependency><gro ...

  4. SpringBoot集成MyBatis的分页插件PageHelper

    [写在前面] 项目的后台管理系统需要展示所有资源信息,select * 虽然方便但数据量过于庞大会严重降低查找效率,页面加载慢,用户体验差.分页自然是必要选择,但原生的方法过于繁杂.MyBatis的分 ...

  5. Springboot集成mybatis通用Mapper与分页插件PageHelper

    Springboot集成mybatis通用Mapper与分页插件PageHelper 插件介绍 通用 Mapper 是一个可以实现任意 MyBatis 通用方法的框架,项目提供了常规的增删改查操作以及 ...

  6. SpringBoot集成MyBatis的分页插件PageHelper(回头草)

    俗话说:好?不吃回头草,但是在这里我建议不管你是好马还是不好马,都来吃吃,带你复习一下分页插件PageHelper. 昨天给各位总结了本人学习springboot整合mybatis第一阶段的一些学习心 ...

  7. springboot整合分页插件PageHelper

    一. 概述 后端开发80%都是查询操作, 而查询经常涉及到数据分页, 分页工具有很多, 本文介绍的是分页插件PageHelper, 工程基于springboot 参考文章: springBoot my ...

  8. SpringBoot整合mybatis+mybatis分页插件

    第一步:相关依赖 <!--web,servlet引入--> <dependency><groupId>org.springframework.boot</gr ...

  9. SpringBoot进阶教程 | 第四篇:整合Mybatis实现多数据源

    这篇文章主要介绍,通过Spring Boot整合Mybatis后如何实现在一个工程中实现多数据源.同时可实现读写分离. 准备工作 环境: windows jdk 8 maven 3.0 IDEA 创建 ...

  10. SpringBoot进阶教程 | 第四篇:整合Mybatis实现多数据源 1

    这篇文章主要介绍,通过Spring Boot整合Mybatis后如何实现在一个工程中实现多数据源.同时可实现读写分离. 准备工作 环境: windows jdk 8 maven 3.0 IDEA 创建 ...

最新文章

  1. R语言使用ggplot2包使用geom_violin函数绘制分组小提琴图(配置显示均值、标准偏差)实战
  2. IBM Rational DOORS通过DXL进行二次开发初试(2)
  3. opencv 人脸检测
  4. 理解Vue 2.5的Diff算法
  5. SQL Server 2005 DTS导入平面数据
  6. mysql mha reference_MySQL MHA配置常见问题
  7. C#使用结构来传递多个参数
  8. 2020年阴历二月二十六 投资理财~读万科财报有感
  9. AlphaFold2: Highly accurate protein structure prediction with AlphaFold笔记
  10. OpenGL光源光照使用范例
  11. 移动应用专项测试的思路和方法
  12. 启用系统保护是灰色的#win10系统
  13. python使用什么来区分代码块_Python 小数据池、代码块以及代码块缓存机制
  14. html实现给微信发红包看照片,微信发红包看图片效果实现
  15. 郑大计算机研究生学硕好还是专硕好,2021郑州大学考研:学硕专硕的区别
  16. 数模分析第五天---判别分析
  17. 转载:【SQL练习】经典SQL练习题
  18. 在linux下解压rar文件
  19. python3 运行you get_You-Get的安装及使用方法
  20. QT之model-delegat-model---QAbstractListModel QAbstractTableModel 与 QItemDelegate关系

热门文章

  1. el-table对于超出长度限制的文本的处理(vue-cli)
  2. 【转】VirtualDOM与diff(Vue实现).MarkDown
  3. EncryptPad—Linux中好用的加密文本编辑器
  4. 定位到文件目录并选定文件
  5. 【译文】Nodejs官方文档(Part 3 断言测试)
  6. 说说ejabberd离线消息踩过的坑
  7. 1.4补充 三态缓存(tristate buffer)与 多路复用器(Multiplexers)
  8. java 调用存储过程structdescriptor_Spring SimpleJdbcCall如何在存储过程调用中为oracle STRUCT指定模式...
  9. php 自定义 base64 解码,php base64 编码与解码实例代码
  10. tcp协议及工作原理浅析_详解TCP/IP网络协议栈底层原理到徒手实现