网站首页> 文章专栏> 查询数据量大时分页怎么处理
查询数据量大时分页怎么处理
原创 时间:2024-03-13 08:22 作者:AI智能 浏览量:1592
分页

  • 查询数据量大时。减少数据的处理量
一,分页插件 PageHelper 进行分页

1,引入Maven(注意版本是否和框架一致性) 这里我使用的是 4.1.4, 截止到 2021 年 11 月 16 日,PageHelper 最新版本为 5.3.0版本

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

2,在Mybatis配置xml,中配置拦截器插件

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <plugins> <plugin interceptor="com.github.pagehelper.PageHelper"> <property name="dialect" value="mysql"/> </plugin> </plugins> </configuration>

3,在spring 配置文件中配置拦截器插件

现在很多项目都是基于 SSM 或者 SpringBoot, 不可能只用到 mybatis 一个框架,往往需要和 Spring、SpringMvc 整合起来用,需要将 mybatis.xml 配置整合到 spring-config.xml 中。

<!--spring和mybatis整合的工厂bean--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:mybatis.xml" /> </bean>

4,在代码中使用(参考)

 // 检查项分页查询
@Override
public ResultObj getUserDevicesList(String userId, Integer pageNo, Integer pageSize) {
    if (StringUtils.isEmpty(userId)){
        return ResultObj.error(ConstantPool.PARAMETER_ERROR,"please check user_id");
    }

    try {
        if (pageNo < 1){
            pageNo = 1;
        }
        if (pageSize > 20){
            pageSize = 20;
        }
      
        PageHelper.startPage(pageNo,pageSize);
        TbDeviceTopExample example = new TbDeviceTopExample();
        example.createCriteria().andUserIdEqualTo(userId)
                .andValidEqualTo(ConstantPool.TRUE);
        Page page = (Page) tbDeviceTopMapper.selectByExample(example);
        long total = page.getTotal();
        List tbDeviceTopList = page.getResult();    /获取数据
        
        
        System.out.println(total);
        System.out.println(JSON.toJSONString(tbDeviceTopList));
    }catch (Exception e){
        e.printStackTrace();
    }
    return null;

}
最后返回

1710317954567.webp

使用Limit分页
1710317966794.webp
使用Mybatis实现分页,核心sql
  1. 接口
  2. mapper.xml
  3. 测试
使用RowBounds分页 (面向对象分页)开发中不建议使用
1710317980115.webp
动动小手 !!!
来说两句吧
最新评论
  • zk、至尊男孩
    支持博主优秀好文

  • 代码王子
    大佬的文章让我对这领域的技术问题有了更深入的了解,尤其是大佬提到的那些“坑点”,我相信能够在实际应用中避免或解决很多问题。谢谢大佬的分享,期待大佬的更多精彩文章,让我们共同学习、进步。