Mybatis分页插件PageHelper简单使用
转载自:https://www.cnblogs.com/ljdblog/p/6725094.html
引言
对于使用Mybatis时,最头痛的就是写分页,需要先写一个查询count的select语句,然后再写一个真正分页查询的语句,当查询条件多了之后,会发现真不想花双倍的时间写count和select,
如下就是项目在没有使用分页插件的时候的语句
<!-- 根据查询条件获取查询获得的数据量 --><select id="size" parameterType="Map" resultType="Long">select count(*) from help_assist_student<where><if test="stuId != null and stuId != ''">AND stu_id likeCONCAT(CONCAT('%',#{stuId,jdbcType=VARCHAR}),'%')</if><if test="name != null and name != ''">AND name likeCONCAT(CONCAT('%',#{name,jdbcType=VARCHAR}),'%')</if><if test="deptId != null">AND dept_id in<foreach item="item" index="index" collection="deptId" open="("separator="," close=")">#{item}</foreach></if><if test="bankName != null">AND bank_name in<foreach item="item" index="index" collection="bankName"open="(" separator="," close=")">#{item}</foreach></if></where></select><!-- 分页查询获取获取信息 --><select id="selectByPageAndSelections" parameterType="cn.edu.uestc.smgt.common.QueryBase"resultMap="BaseResultMap">select * from help_assist_student<where><if test="parameters.stuId != null and parameters.stuId != ''">AND stu_id likeCONCAT(CONCAT('%',#{parameters.stuId,jdbcType=VARCHAR}),'%')</if><if test="parameters.name != null and parameters.name != ''">AND name likeCONCAT(CONCAT('%',#{parameters.name,jdbcType=VARCHAR}),'%')</if><if test="parameters.deptId != null">AND dept_id in<foreach item="item" index="index" collection="parameters.deptId"open="(" separator="," close=")">#{item}</foreach></if><if test="parameters.bankName != null">AND bank_name in<foreach item="item" index="index" collection="parameters.bankName"open="(" separator="," close=")">#{item}</foreach></if></where>order by dept_id,stu_idlimit #{firstRow},#{pageSize}</select>
可以发现,重复的代码太多,虽然说复制粘贴简单的很,但是文件的长度在成倍的增加,以后翻阅代码的时候头都能大了。
于是希望只写一个select语句,count由插件根据select语句自动完成。找啊找啊,发现PageHelperhttps://github.com/pagehelper/Mybatis-PageHelper 符合要求,于是就简单的写了一个测试项目
1,配置分页插件:
直接从官网上copy的如下:
Config PageHelper1. Using in mybatis-config.xml<!-- In the configuration file, plugins location must meet the requirements as the following order:properties?, settings?, typeAliases?, typeHandlers?, objectFactory?,objectWrapperFactory?, plugins?, environments?, databaseIdProvider?, mappers? --> <plugins><plugin interceptor="com.github.pagehelper.PageInterceptor"><!-- config params as the following --><property name="param1" value="value1"/></plugin> </plugins> 2. Using in Spring application.xmlconfig org.mybatis.spring.SqlSessionFactoryBean as following:<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- other configuration --><property name="plugins"><array><bean class="com.github.pagehelper.PageInterceptor"><property name="properties"><!-- config params as the following --><value>param1=value1</value></property></bean></array></property> </bean>
我使用第一中方法:
<!-- 配置分页插件 --><plugins><plugin interceptor="com.github.pagehelper.PageInterceptor"><!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库--><property name="helperDialect" value="mysql"/></plugin></plugins>
其余的关于mybatis整合spring的内容就不用提了。
2,编写mapper.xml文件
测试工程就不复杂了,简单的查询一个表,没有条件
<select id="selectByPageAndSelections" resultMap="BaseResultMap">SELECT *FROM docORDER BY doc_abstract</select>
然后在Mapper.java中编写对应的接口
public List<Doc> selectByPageAndSelections();
3,分页
@Service public class DocServiceImpl implements IDocService {@Autowiredprivate DocMapper docMapper;@Overridepublic PageInfo<Doc> selectDocByPage1(int currentPage, int pageSize) {PageHelper.startPage(currentPage, pageSize);List<Doc> docs = docMapper.selectByPageAndSelections();PageInfo<Doc> pageInfo = new PageInfo<>(docs);return pageInfo;} }
参考文档说明,我使用了PageHelper.startPage(currentPage, pageSize);
我认为这种方式不入侵mapper代码。
其实一开始看到这段代码时候,我觉得应该是内存分页。其实插件对mybatis执行流程进行了增强,添加了limit以及count查询,属于物理分页
再粘贴一下文档说明中的一段话
4. 什么时候会导致不安全的分页?PageHelper 方法使用了静态的 ThreadLocal 参数,分页参数和线程是绑定的。只要你可以保证在 PageHelper 方法调用后紧跟 MyBatis 查询方法,这就是安全的。因为 PageHelper 在 finally 代码段中自动清除了 ThreadLocal 存储的对象。如果代码在进入 Executor 前发生异常,就会导致线程不可用,这属于人为的 Bug(例如接口方法和 XML 中的不匹配,导致找不到 MappedStatement 时), 这种情况由于线程不可用,也不会导致 ThreadLocal 参数被错误的使用。但是如果你写出下面这样的代码,就是不安全的用法:PageHelper.startPage(1, 10); List<Country> list; if(param1 != null){list = countryMapper.selectIf(param1); } else {list = new ArrayList<Country>(); } 这种情况下由于 param1 存在 null 的情况,就会导致 PageHelper 生产了一个分页参数,但是没有被消费,这个参数就会一直保留在这个线程上。当这个线程再次被使用时,就可能导致不该分页的方法去消费这个分页参数,这就产生了莫名其妙的分页。上面这个代码,应该写成下面这个样子:List<Country> list; if(param1 != null){PageHelper.startPage(1, 10);list = countryMapper.selectIf(param1); } else {list = new ArrayList<Country>(); } 这种写法就能保证安全。如果你对此不放心,你可以手动清理 ThreadLocal 存储的分页参数,可以像下面这样使用:List<Country> list; if(param1 != null){PageHelper.startPage(1, 10);try{list = countryMapper.selectAll();} finally {PageHelper.clearPage();} } else {list = new ArrayList<Country>(); } 这么写很不好看,而且没有必要。
4,结果
controller层中简单的调用然后返回json字符串如下:可以看出,结果基于doc_abstract排序后返回1-10条的数据
结语
尽量不要重复造轮子。
Mybatis分页插件PageHelper简单使用相关推荐
- mybatis分页插件pageHelper简单实用
转载自 http://blog.csdn.net/Smile_Miracle/article/details/53185655 工作的框架spring springmvc mybatis3 首先使用分 ...
- mybatis分页插件PageHelper简单应用
--添加依赖 <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper --> <depend ...
- 解决使用mybatis分页插件PageHelper的一个报错问题
解决使用mybatis分页插件PageHelper的一个报错问题 参考文章: (1)解决使用mybatis分页插件PageHelper的一个报错问题 (2)https://www.cnblogs.co ...
- (转)淘淘商城系列——MyBatis分页插件(PageHelper)的使用以及商品列表展示
http://blog.csdn.net/yerenyuan_pku/article/details/72774381 上文我们实现了展示后台页面的功能,而本文我们实现的主要功能是展示商品列表,大家要 ...
- Mybatis分页插件PageHelper使用教程(图文详细版)
Mybatis分页插件PageHelper使用教程(图文详细版) 1.配置 2.后台代码 controller类 html页面 html页面效果图 1.配置 小编的项目是springBoot项目,所以 ...
- MyBatis分页插件PageHelper使用练习
转载自:http://git.oschina.net/free/Mybatis_PageHelper/blob/master/wikis/HowToUse.markdown 1.环境准备: 分页插件p ...
- 【MyBatis】MyBatis分页插件PageHelper的使用
转载自 https://www.cnblogs.com/shanheyongmu/p/5864047.html 好多天没写博客了,因为最近在实习,大部分时间在熟悉实习相关的东西,也没有怎么学习新的东西 ...
- MyBatis学习总结(17)——Mybatis分页插件PageHelper
2019独角兽企业重金招聘Python工程师标准>>> 如果你也在用Mybatis,建议尝试该分页插件,这一定是最方便使用的分页插件. 分页插件支持任何复杂的单表.多表分页,部分特殊 ...
- mybatis 分页插件PageHelper的简单使用
分页方式的分类: 逻辑分页 物理分页 MyBatis-PageHelper 的使用: 首先在pom.xml配置文件中增加相关的插件. 插件地址:https://github.com/pagehelpe ...
最新文章
- 启明云端分享| SSD212 SPI+RGB点屏参考
- RabbitMQ学习之消息可靠性及特性
- vs 窗体连接mysql_vs2008 c#开发windows窗体程序,怎么连接数据库?
- 使用Quarkus调试容器中的系统测试(视频)
- labelme新版本的使用须知
- 程序员必看书籍之二:编程语言实现模式
- 深度篇——人脸识别(二) 人脸识别代码 insight_face_pro 项目讲解
- 计算机无纸化考试合卷答题笔记卡,中级会计职称无纸化答题技巧
- 【解决有些jar包依赖就是下载不下来】
- 步进电机扭矩计算公式
- PHP 判断操作系统位数
- java 加水印_Java添加水印(图片水印,文字水印)
- 使用linux内核仿真ZNS(zoned namespace SSD)
- Win10家庭中文版( 连接远程桌面要求的函数不受支持、这可能是由于 CredSSP 加密 Oracle 修正 )
- 腾讯T1~T9级别工程师具备专业的能力及知识点总结。
- variant 类型
- nginx配置文件映射外网服务器
- 华为 HCIA-AI V3.0 认证人工智能工程师考试
- zynq操作系统: jffs2文件系统的错误异常
- MAC-word打开时提示无法使用公用模版解决
热门文章
- memoryerror: Unable to allocate array with shape (60000, 28, 28) and data ty
- Python与常见加密方式
- python中frameset中的元素怎么识别_python3.6+selenium实现操作Frame中的页面元素
- Mysql数据库有两种安装方法
- VLDB 2021 EAB最佳论文:深度解析机器学习的基数估计为何无法实现?
- 多种数据形式下智能问答的应用解读
- 直播 | WWW 2021论文解读:基于隐私保护的模型联邦个性化
- python pandas.DataFrame选取、修改数据
- ClickHouse【环境搭建 02】设置用户密码的两种方式(明文+SHA256)及新用户添加及只读模式 Cannot execute query in readonly mode 问题解决
- 南大计算机考研录取,南京大学拟录取名单公示,初试最高446分,推免占比竟高达75%...