首页 > 其他分享 >Mybatis/Plus 分页查询

Mybatis/Plus 分页查询

时间:2024-09-04 14:26:39浏览次数:4  
标签:pageDto ess 分页 查询 Plus Mybatis id es

 

分页查询的原理是通过将大数据量集分割成较小的部分来返回结果,以减少一次性加载和显示的数量。

接受分页参数:在分页查询中,通常会接收两个关键的参数——当前页码(current)和每页显示的数据量(size)。这些参数决定了用户希望查看哪一部分数据。

计算偏移量:根据当前页码和每页显示数据量,计算出从数据库中哪一行数据开始获取。偏移量公式:

      start = (current - 1)* size; start 的值就是数据集中的起始位置。

执行分页查询:在SQL查询中使用 Limit 字句来限制查询返回的记录数。Limit 接受两个参数——偏移量 start 和 每页显示的记录数 size,指示数据库从偏移量处开始,返回指定数量的记录。如:

select * from table_name limit start, size;
-- 这条语句将从 start 位置开始获取,获取 size 条记录。

   还有 像 PageHelper 或 RowBounds 这样的分页工具,分页查询原理虽然与 Limit 查询类似,但过程更加简化和自动化。通过简化分页原理,自动处理分页参数并返回分页后的数据。

构建查询条件:分页查询中,通常还会结合其他条件(如筛选条件),来进一步缩小查询范围。条件可以通过 where 子句进行过滤,以满足查询要求。

返回结果:数据库执行查询后,将结果集返回给应用程序。程序将结果进行展示,用户使用时可以通过调整页码和每页记录数,查看不同的部分。

通过分页查询,系统可以有效减少内存占用和网络传输的压力,提升响应速度,特别是在数据量非常大的情况下。

 

1. 在SQL内分页

SQL 使用 Limit。可以直接单表使用,也可以多表实现。

只返回数据,不返回查询总数。    

分页查询类:

/**
 * 分页
 */
@Data
public class PageShowDto {

    /** 初始页 */
    private Integer current;
    /** 数量 */
    private Integer size;
    /** 开始 */
    private Integer start;

}

 

Service实现类:

    /**
     * 查询
     *
     * @param pageDto  分页
     * @param steamDto 条件
     * @return 信息
     */
    @Override
    public List<ExerciseSchemeSteamDto> findExerciseType(ExerciseSchemeSteamDto steamDto, PageShowDto pageDto) {

        pageDto.setStart((pageDto.getCurrent() - 1) * pageDto.getSize());

        return exerciseSchemeAndSteamMapper.findExerciseSchemeSteamType(steamDto, pageDto);

    }
current--起始页;
size--每页条数;
pageDto.getCurrent() - 1) * pageDto.getSize()-- 如:(current 3 - 1) * size 10 为 20;此时 start 为 20;

Mappe接口:

    /** 查询 */
    List<ExerciseSchemeSteamDto> findExerciseSchemeSteamType(@Param("steamDto") ExerciseSchemeSteamDto steamDto, @Param("pageDto") PageShowDto pageDto);

 

XML编写SQL:

    <!-- 查询两个表   -->    
    <select id="findExerciseSchemeSteamType"
            resultType="com.control.interactive.entity.dto.ExerciseSchemeSteamDto">
        select
        es.id,
        es.stage_name as stageName,
        es.condition_scenario as conditionScenario,
        es.red_team_action as redTeamAction,
        ess.team_id as teamId,
        ess.team_name as teamName,
        ess.action_command as actionCommand,
        ess.scheme_id as schemeId
        from t_exercise_scheme es
            left join t_exercise_scheme_team ess
        on es.id = ess.scheme_id
        <where>
            <if test="steamDto.stageName != null and steamDto.stageName != ''">
                es.stage_name like concat('%', #{steamDto.stageName}, '%')
            </if>
        </where>
        order by es.id
        <if test="pageDto != null">
            limit #{pageDto.size} offset #{pageDto.start}
        </if>
    </select>
current--起始页;
size--每页条数;
pageDto.getCurrent() - 1) * pageDto.getSize()-- 如:(current 3 - 1) * size 10 为 20;此时 start 为 20;
此时分页查询是从 第21条 数据开始截取,每页 10条 数据。

 

查询直接传递参数 current 与 size。想进一步使用条件过滤,直接传递相应的字段,如 name-模糊查询等等...

 

优化返回结果,可以使用 `com.baomidou.mybatisplus.extension.plugins.pagination.Page` 的 Page<> 返回。

 

2. 使用 PageHelper 插件

PageHelper 是 Mybatis 中常用的分页插件。再查询SQL前,自动处理分页逻辑并为查询语句添加适当的 Limit 字句。

 

注入依赖:

        <!-- PageHelper 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.6</version>
        </dependency>

PS:注入依赖使用 注意 与 JSqlParser 的版本冲突,根据情况进行升降 pagehelper 版本。

 

自定义分页查询类,用于前端传值:

/**
 * 分页
 */
@Data
public class PageShowDto {

    /** 初始页 */
    private Integer current;
    /** 数量 */
    private Integer size;

}

 

ServiceImpl:

初始化分页:在调用查询方法前,通过 PageHelper.startPage(current, size) 设置当前页码和每页显示的记录数。

 ~~ PageHelper.startPage(1, 10);

    /**
     * 查询
     *
     * @param pageDto 分页
     * @param steamDto        条件
     * @return 信息
     */
    @Override
    public R<PageInfo<ExerciseSchemeSteamDto>> findExercise(PageShowDto pageDto, ExerciseSchemeSteamDto steamDto) {

        // 分页参数设置
        PageHelper.startPage(pageDto.getPageNum(), pageDto.getPageSize());
        List<ExerciseSchemeSteamDto> exerciseSchemeSteam = exerciseSchemeAndSteamMapper.findExerciseSchemeSteam(steamDto);

        PageInfo<ExerciseSchemeSteamDto> steamPageInfo = new PageInfo<>(exerciseSchemeSteam);
        return R.ok(steamPageInfo);
    }

PageHelper 拦截SQL语句,再执行SQL前自动添加 Limit 和 Offset 子句,便于在数据库表中查询所需数据。

 

XML SQL 编写:

    /** 查询 */
    List<ExerciseSchemeSteamDto> findExerciseSchemeSteam(@Param("steamDto") ExerciseSchemeSteamDto steamDto);

 

    <!-- 查询-->
    <select id="findExerciseSchemeSteam"
            resultType="com.hrzn.control.interactive.blue.entity.dto.ExerciseSchemeSteamDto">
        select
        es.id as id,
        es.stage_name as stageName,
        es.condition_scenario as conditionScenario,
        es.red_team_action as redTeamAction,
        ess.team_id as teamId,
        ess.team_name as teamName,
        ess.action_command as actionCommand,
        ess.scheme_id as schemeId
        from t_exercise_scheme es left join t_exercise_scheme_team ess
        on es.id = ess.scheme_id
        <where>
            <if test="steamDto.stageName != null and steamDto.stageName != ''">
                es.stage_name like concat('%', #{steamDto.stageName}, '%')
            </if>
        </where>
        order by es.id;
    </select>

后台会通过 PageHelper 将SQL 改为 select (字段) from (表名) limit 0, 10;

 

返回结果:查询完成后,优化查询返回结果可以使用 PageInfo<>,PageHelper 会将结果封装到一个 PageInfo对象,其中包含查询结果、总数据量、总页数等分页信息。

 

优点:

  简化分页代码:只需要调用 startPage() 方法,分页逻辑自动处理。

  集成度高:与 Mybatis 无缝集成,直接应用于现有的 Mybatis 查询。

 

简单使用:https://www.cnblogs.com/warmNest-llb/p/18120512

 

3. 使用 RowBounds 分页

RowBounds 是 Mybatis 自带的一种分页处理方式,通过逻辑分页(在内存中分页)来控制查询结果的范围。

 

RowBounds:

 

构建查询:

    /**
     * 查询
     *
     * @param schemeSteamPage 条件
     * @param pageDto 分页
     * @return true
     */
    @Override
    public List<ExerciseSchemeSteamDto> findExerciseRowBounds(ExerciseSchemeSteamDto schemeSteamPage, PageShowDto pageDto) {
        RowBounds rowBounds = new RowBounds((pageDto.getCurrent() - 1) * pageDto.getSize(), pageDto.getSize());
        return exerciseSchemeAndSteamMapper.findExerciseSchemeSteamRow(schemeSteamPage, rowBounds);
    }

构建 RowBounds 对象:通过 创建一个 RowBounds 对象,传入偏移量 offsert 和 每页记录数 limit;

new RowBounds((pageDto.getCurrent() - 1) * pageDto.getSize(), pageDto.getSize()) 等价于 new RowBounds(offset, size);

 offset 从哪行数据开始,size 多少条数据。

 

XML 编写 SQL:

    /** 查询 */
    List<ExerciseSchemeSteamDto> findExerciseSchemeSteamRow(@Param("steamDto") ExerciseSchemeSteamDto steamDto, RowBounds rowBounds);

 

    <!-- 演练查询-->
    <select id="findExerciseSchemeSteam"
            resultType="com.hrzn.control.interactive.blue.entity.dto.ExerciseSchemeSteamDto">
        select
        es.id as id,
        es.stage_name as stageName,
        es.condition_scenario as conditionScenario,
        es.red_team_action as redTeamAction,
        ess.team_id as teamId,
        ess.team_name as teamName,
        ess.action_command as actionCommand,
        ess.scheme_id as schemeId
        from t_exercise_scheme es left join t_exercise_scheme_team ess
        on es.id = ess.scheme_id
        <where>
            <if test="steamDto.stageName != null and steamDto.stageName != ''">
                es.stage_name like concat('%', #{steamDto.stageName}, '%')
            </if>
        </where>
        order by es.id;
    </select>

 

 

查询与分页:Mybatis 执行查询时,将结果集取回后,根据 RowBounds 进行内存级别的分页处理。这种方式下分页逻辑是在应用程序内存中执行的,而不是在SQL查询中添加 Limit 子句。

 

 

优点:

  无需改动原始SQL:可以直接作用于已有的 Mybatis 查询。

 

缺点:

  适合小数据集:由于是内存中处理分页逻辑,对于大数据集来说性能较差。通常不推荐在大数据集上使用 RowBounds 进行分页。

 

 

4. 总结

 直接在SQL内分页,简单粗暴。

 PageHelper 自动化处理分页查询,拦截并改写 SQL,性能高,适合大数据集,推荐在 Mybatis 中使用。

 RowBounds 则是基于内存的分页方式,简单直接,但对于大数据集性能不佳,通常只适合处理小数据集的分页。

 

 


 

标签:pageDto,ess,分页,查询,Plus,Mybatis,id,es
From: https://www.cnblogs.com/warmNest-llb/p/18395605

相关文章

  • MyBatis 源码解析:DefaultSqlSession 功能解析
    摘要DefaultSqlSession是MyBatis中的核心类,负责执行SQL语句和管理事务。在日常开发中,我们经常会通过SqlSession来执行数据库的增删改查操作。你是否想深入了解DefaultSqlSession的内部实现机制?本文将通过自定义实现一个DefaultSqlSession类,带你全面解析MyBatis......
  • Mybatis学习笔记
    本笔记基于【尚硅谷新版SSM框架全套视频教程,Spring6+SpringBoot3最新SSM企业级开发】https://www.bilibili.com/video/BV1AP411s7D7?vd_source=a91dafe0f846ad7bd19625e392cf76d8总结资料获取网址:https://www.wolai.com/v5Kuct5ZtPeVBk4NBUGBWFMyBatis实践:提高持久层数据......
  • mybatis-plus批量增加、批量修改样例+建表语句+postman接口
    使用mybatis-plus开发中会遇到数据量多的情况下,插入和修改效率低,主要原因是“新增“和“修改”方法是对一条数据进行处理的,如果有一万条数据就会和数据库交互一万次所以效率就低。如何提高效率就需要批量操作,如下展示批量插入和批量修改的代码,数据库使用mysql。1、建表语句CREA......
  • MyBatis 一级缓存原理
    优质博文:IT-BLOG-CN一、一级缓存配置MyBatis一级缓存默认是开启的。如果需要显示的开启,需要在MyBaits配置文件中<settings>标签中添加如下语句:<settings> <settingname="localCacheScope"value="SESSION"/></settings>value共有两个选项,SESSION或者STATEMENT,默认是......
  • 【Spring Boot】整合MyBatis
    **整合MyBatis**前言SpringBoot和MyBatis都是非常流行的Java框架。SpringBoot简化了Spring应用的开发,而MyBatis则是一个优秀的持久层框架,支持自定义SQL、存储过程以及高级映射。mybatis官方文档:http://mybatis.org/spring-boot-starter/myba......
  • FastAPI+Vue3零基础开发ERP系统项目实战课 20240831上课笔记 查询参数和分页实现
    回顾获取路径参数什么是路径参数?/user/{id}什么时候使用?需要传递参数怎么实现类型转换?声明参数的类型怎么捕获文件路径?{file_path:path}什么是查询参数查询字符串是键值对的集合,这些键值对位于URL的?之后,以&分隔。http://127.0.0.1:8000/items/?skip=0&limit=10......
  • SpringBoot3.x+MyBatisPlus+druid多数据源配置
    1引言本章主要介绍SpringBoot3.x多数据源配置,以及在此基础上配置分页拦截,自动填充功等功能,源码链接在文章最后。下面列出几个重要文件进行介绍。2项目结构整体项目结构如下,主要介绍配置文件和配置类。3主要代码3.1pom.xml注意SpringBoot3.x对应依赖为mybatis-plu......
  • SpringBoot项目常用配置文件MybatisPlusConfig、RedisConfig、RedissonConfig、Swagge
    MybatisPlusConfig:@Configuration@MapperScan("com.yupi.usercenter.mapper")publicclassMybatisPlusConfig{@BeanpublicMybatisPlusInterceptormybatisPlusInterceptor(){MybatisPlusInterceptorinterceptor=newMybatisPlusInterc......
  • Vite2.0+ElementPlus+Koa2+Mongo全栈开发通用后台系统Vue3
    Vite2.0+ElementPlus+Koa2+Mongo全栈开发通用后台系统Vue3前言当前基于NodeJs框架的全栈工程实践非常之火,作为一个很长时间未接触代码的前程序猿。一直有点手痒痒,想尝试一下这种全新的编程体验,于是就重新开始了填坑的不归之路。这一套框架是基于现在的前后台分离的指导原则来......
  • TS4+Vite+Vitest+Vitepress Vue3.3 自主打造媲美ElementPlus的组件库
    TS4+Vite+Vitest+VitepressVue3.3自主打造媲美ElementPlus的组件库这个问题看起来是想要创建一个类似ElementPlus的Vue组件库,并且使用TypeScript、Vite、Vitest和Vitepress进行开发。以下是一个简化的指南,用于创建一个自己的Vue组件库项目框架。安装必要的工具:npm......