MyBatis分页组件--PageHelper
2024-08-31 01:47:52
一.介绍
PageHelper是国内非常优秀的一款开源的 mybatis 分页插件,它支持基本主流与常用的数据库,例如 Oracle、Mysql、MariaDB、SQLite、Hsqldb 等。
官网网址:https://pagehelper.github.io/
GitHub地址:https://github.com/pagehelper/Mybatis-PageHelper
How To Use:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/en/HowToUse.md
二.基本使用
1.第一步:导入Maven坐标
<!-- 集中定义依赖版本号 -->
<properties>
<pagehelper.version>5.1.2</pagehelper.version>
</properties>
<dependencies>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>${pagehelper.version}</version>
</dependency>
</dependencies>
2.第二步:在Spring配置文件中配置拦截器插件
applicationContext-dao.xml
<!-- 配置sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 配置实体类别名 -->
<property name="typeAliasesPackage" value="cn.dintalk.domain"/> <!-- 配置pageHelper分页的插件 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<!-- 这里的几个配置主要演示如何使用,如果不理解,一定要去掉下面的配置 -->
<property name="properties">
<value>
<!-- 可区分数据库 -->
helperDialect=mysql
<!-- 是否合理分页,针对首页尾页越界 -->
reasonable=true
</value>
</property>
</bean>
</array>
</property> </bean>
Tips: helperDialect:分页插件自定检测当前的数据库连接,选择合适的分页方式,可配置helperDialect属性来指定分页插件使用哪种方言,可使用以下缩写值:oracle, mysql, mariadb, sqlite,等等。还有其他的配置,需要时请查阅官方文档。
3.第三步:service层分页
PageHelper的基本使用有6种,可见官方文档。这里介绍PageHelper.startPage的静态方法。
dao层代码
// 查询所有
List<Company> findAll();
dao层映射.xml
<!-- 查询所有 -->
<select id="findAll" resultMap="baseResultMap">
select * from sh_company
</select>
service层代码
//使用PageHelper分页查询,page:当前页面,size:每页显示数量
public PageInfo findPageByHelper(int page, int size) {
//1.调用静态方法,开始分页
PageHelper.startPage(page,size);
//2.照常调用
List<Company> companies = companyDao.findAll();
return new PageInfo(companies);
}
Tips: 在需要分页的MyBatis查询方法前调用 PageHelper.startPage 静态方法即可。格外需要注意的是:(紧跟在这个方法后的第一个MyBatis查询方法或被进行分页),因此在使用的时候留意顺序。
返回值PageInfo中包含了分页页面所需的一切信息,包括展示的数据及页码、上一页等等。在页面取值的时候可以跟到PageInfo源码中查看清楚即可!
关注微信公众号,随时随地学习
最新文章
- C#中,双屏/两屏/三屏/多屏跳转判断
- Java c3p0连接池
- Google V8编程详解(序)Cloud App
- 不用插件 让Firefox 支持网页翻译
- JAVA6开发WebService (三)——几个概念
- 四、Handler(WSGIHandler)
- Emacs常用命令
- node.js的npm详解
- SEDA工作笔记(一)
- mysql 安装过程中的错误:my-template.ini could not be processed and written to XXX\my.ini.Error code-1
- codility上的问题(26) Hydrogenium 2013
- USACO 4.1 Fence Loops(Floyd求最小环)
- ajaxFileUpload 报这错jQuery.handleError is not a function
- Asynchronous JS: Callbacks, Listeners, Control Flow Libs and Promises
- android 模拟器对应键盘快捷键
- sql select中加入常量列
- excel2007VBA绘图2
- DataGridView不显示未绑定的列-AutoGenerateColumns
- Alpha发布评价
- VS中一些不常用的快捷键