myBatis-分页

1.前言

MyBatis,作为目前流行的ORM框架,大大方便了日常开发。而对于分页查询,虽然可以通过SQL的limit语句实现,但是比较繁琐。

1.1.Limit方式

以前的分页查询,拼接sql 语句:

  BookMapper.java接口:

//根据limit 语句拼接,进行相应的分页
List<Book> selectBySQL(@Param("start")int start, @Param("offset") int offset);

  BookMapper.xml SQL语句:

<!-- 分页查询 -->
<select id="selectBySQL" resultMap="BaseResultMap" parameterType="com.zking.ssm.model.Book" >
    select
    <include refid="Base_Column_List" />
    from t_book
    limit #{start},#{offset}
</select>

这种分页是放置在sql 语句里面的, 很可能每一个查询的sql 语句都要在最后添加一下这个语句,并且还非得传入两个参数,可重复利用性低,尤其是条件查询时。

1.2.RowBounds方式

通过RowBounds实现分页和通过数组方式分页原理差不多,都是一次获取所有符合条件的数据,然后在内存中对大数据进行操作,实现分页效

果。(不推荐使用

 一次性从数据库获取的数据可能会很多,对内存的消耗很大,可能导致性能变差,甚至引发内存溢出。

  BookMapper.java接口:

List<Book> selectBySQL(RowBounds rowBounds);

  BookMapper.xml SQL语句:

语句与前面的一样,不具有侵入性。 不用改变相应的sql语句。 只需要在要分页的方法接口上添加 RowBounds 对象参数即可。

<select id="selectBySQL" resultType="com.zking.ssm.model.Book">
select <include refid="Base_Column_List"/> from t_book
</select>

  测试

 

@Test
public void demo(){
    int page=1;
    int rows=10;
    RowBounds rowBounds=new RowBounds((page-1)*rows,rows);
    List<Book> books = bookService.selectBySQL(rowBounds);
    books.forEach(System.out::println);
}

 

 

 

2.PageHelper介绍

PageHelper 是适用于 MyBatis 框架的一个分页插件,使用方式极为便捷,支持任何复杂的单表、多表分页查询操作。它支持基本主流与常用的数据库,例如mysql、oracle、mariaDB、DB2、SQLite、Hsqldb等。

官方网站:https://pagehelper.github.io/

下载地址:https://github.com/pagehelper/Mybatis-PageHelper

2.1.添加依赖

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.2</version>
</dependency>

2.2.配置插件

在MyBatis-config.xml中添加 `<plugins>`。

复制代码
<configuration>
      <typeAliases></typeAliases>

    <plugins>
        <!-- com.github.pagehelper为PageHelper类所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

      <environments>...</environments>
</configuration>
复制代码

 

 2.3.PageHelper.startPage

在你需要进行分页的Mybatis方法前调用PageHelper.startPage静态方法即可,紧跟在这个方法后的第一个Mybatis查询方法会被进行分页。

 注意:只有紧跟着PageHelper.startPage()的sql语句才被pagehelper起作用

//设置分页处理
if (null != pageBean && pageBean.isPagination()) {
PageHelper.startPage(pageBean.getPage(), pageBean.getRows());
}
List<Book> books = bookService.selectAllBooks();
for(Book book : books){
System.out.println(book);
}

2.4.获取分页信息

使用插件后,查询实际返回的是Page<E>,而非List<E>,Page继承了ArrayList,同时还包含分页相关的信息。

Page<Book> page = (Page<Book>)list;
System.out.println("页码:" + page.getPageNum());
System.out.println("页大小:" + page.getPageSize());
System.out.println("总记录:" + page.getTotal());

使用PageInfo方式:

PageInfo pageInfo = new PageInfo(list);
System.out.println("页码:" + pageInfo.getPageNum());
System.out.println("页大小:" + pageInfo.getPageSize());
System.out.println("总记录:" + pageInfo.getTotal());
posted @   孔武  阅读(85)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示