Springboot---分页

本文介绍了在SpringBoot中使用SQL分页和PageHelper插件进行分页的方法。针对SQL分页的局限性,提出了利用主键索引进行优化。详细讲述了PageHelper的配置和使用,包括在UserMapper接口、Map.xml文件和UserController中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考:springboot 中 分页实现SpringBoot分页插件PageHelper

目录

1. sql分页

2. 插件分页-PageHelper

2.1 插件依赖

2.2 配置application.yml文件

2.3 使用

2.3.1 UserMapper接口

2.3.2 Map.xml文件

2.3.3 UserController


1. sql分页

  • 语句样式: MySQL中,可用如下方法: SELECT * FROM 表名称 LIMIT ${offset},${limit}

  • 适应场景: 适用于数据量较少的情况(元组百/千级)

  • 原因/缺点: 全表扫描,速度会很慢 且 有的数据库结果集返回不稳定(如某次返回1,2,3,另外的一次返回2,1,3). Limit限制的是从结果集的M位置处取出N条输出,其余抛弃.

eg:

  <select id="list" resultType="com.sqlb.pojo.Article">
        select
        <include refid="Base_Column_List"/>
        from article
        <where>
            <if test="id != null and id != ''">and id = #{id}</if>
            <if test="author != null and author != ''">and author = #{author}</if>
            <if test="createTime != null and createTime != ''">and create_time = #{createTime}</if>
            <if test="typeName != null and typeName != ''">and type_name = #{typeName}</if>
            <if test="imageUrl != null and imageUrl != ''">and image_url = #{imageUrl}</if>
            <if test="content != null and content != ''">and content = #{content}</if>
        </where>
        <choose>
            <when test="createTime != null and createTime.trim() != ''">
                order by ${createTime}
            </when>
            <otherwise>
                order by id desc
            </otherwise>
        </choose>
        <if test="offset != null and limit != null">
            limit #{offset}, #{limit}
        </if>
    </select>

1.1 分页优化

普通分页:SELECT * FROM 表名称 LIMIT ${offset},${limit}

limit 10000,20的意思扫描满足条件的10020行,扔掉前面的10000行,返回最后的20行,问题就在这里。当数据量达到十万百万级别时,性能就会很差;

优化分页:使用主键索引来优化分页查询。“子查询/连接+索引”快速定位元组的位置,然后再读取元组

注意:当 select 的列与 order by 完全对应时,order by 会一直使用索引;

针对普通分页:select * from sys_data order by id desc limit 500000, 10 //未使用主键索引,直接查询出数据,需要扫描500010行,扔掉前面的500000行;

优化通过子查询启用 id 索引(主键索引)检索出第 50 w 条数据的 id,然后取后面或前面的 10 条

//升序
select * from sys_data where id > (select id from sys_data order by id limit 500000, 1) limit 10;
//降序
select * from sys_data where id > (select id from sys_data order by id desc limit 500000, 1) limit 10;

 

2. 插件分页-PageHelper

2.1 插件依赖

使用pagehelper插件

<!-- springboot分页插件 -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <!-- 特别注意版本问题,不同版本可能会报错 -->
    <version>1.2.3</version>
</dependency>

2.2 配置application.yml文件

# 分页配置,针对mysql
pagehelper:
  helper-dialect: mysql
  reasonable: true
  support-methods-arguments: true
  params: count=countSql

2.3 使用

2.3.1 UserMapper接口

import java.util.List;

public interface UserMapper {
  List<User> getAllUsers();
}

2.3.2 Map.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.edu.cqu.mapper.UserMapper">
    <!--查询出所有的用户-->
      <select id="getAllUsers"  resultType="User">
        SELECT * FROM user
    </select>
</mapper>

2.3.3 UserController

核心代码:PageHelper.startPage(pageNum, pageSize);

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping(value = "/user")
public class UserController {

  private Logger logger = LoggerFactory.getLogger(UserController.class);

  @Resource
  private UserMapper userMapper;

  @RequestMapping(value = "/allUsers")
  public String list(Model model, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {

    //引入分页查询,使用PageHelper分页功能在查询之前传入当前页,然后多少记录
    PageHelper.startPage(pageNum, pageSize);
    //startPage后紧跟的这个查询就是分页查询
    List<User> users = userMapper.getAllUsers();

    //需要把Page包装成PageInfo对象才能序列化。该插件默认实现了一个PageInfo,也可自己实现一个分页数据类pageinfo
    //使用PageInfo包装查询结果,只需要将pageInfo交给页面就可以
    PageInfo pageInfo = new PageInfo<User>(users, 5);
    model.addAttribute("pageInfo", pageInfo);

    //获得当前页
    model.addAttribute("pageNum", pageInfo.getPageNum());
    //获得一页显示的条数
    model.addAttribute("pageSize", pageInfo.getPageSize());
    //是否是第一页
    model.addAttribute("isFirstPage", pageInfo.isIsFirstPage());
    //获得总页数
    model.addAttribute("totalPages", pageInfo.getPages());
    //是否是最后一页
    model.addAttribute("isLastPage", pageInfo.isIsLastPage());
    return "user/list";
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值