MyBatis教程[4]----分页原理及实现


MyBatis的分页查询需要手动实现,MyBatis并没有提供现成的分页功能。接下来跟着本文章来一步一步实现它。

1.需求明确

首先要明确分页查询SQL语句怎么写:

SELECT * FROM `user` LIMIT startIndex,count

startIndex:指定从第哪一条条记录开始查询(不包含当前记录,即实际是从startIndex+1开始的)
count: 指定查询多少条数据

  • count是人为指定的,即需要一页显示多少条数据。
  • startIndex是程序计算出来的,取决于当前查询的页数和每页的记录数。计算方式是:(当前要查询的页码-1)* 每页要查询的记录数。

此外,还需要得到总记录数,总页数。这些可能都是需要在前端显示的。

2.编写Page类

新建page包并在包下新创建Page类,代码如下:

package com.yky.springboot.page;

import java.util.List;

public class Page<T> {
   
    //每页显示的记录数
    private int lineSize = 5;

    //总记录数
    private long totalRecord;

    //用户指定的页数
    private int currentPage;

    //起始位置
    private long startIndex;

    //总页数
    int pageCount;

    List<T> list;

    public Page(int currentPage, long totalRecord, int lineSize) {
   
        this.currentPage = currentPage;
        this.totalRecord = totalRecord;
        this.lineSize = lineSize;

        //计算出pageCount
        this.pageCount = (int) ((totalRecord % lineSize) != 0 ? ((totalRecord / lineSize) + 1) : (totalRecord / lineSize));

        //计算出起始位置,注意,从0下标开始
        this.startIndex = (currentPage - 1) * lineSize;
    }

    public long getStartIndex() {
   
        return (currentPage - 1) * lineSize;
    }

    public void setStartIndex(long startIndex) {
   
        this.startIndex = startIndex;
    }

    public int getLineSize() {
   
        return lineSize;
    }

    public void setLineSize(int lineSize) {
   
        this.lineSize = lineSize;
    }

    public long getTotalRecord() 
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值