• 9、MyBatis分页插件


    学习资源:动力节点《2020最新MyBatis教程【IDEA版】-MyBatis从入门到精通》



    1、limit 分页

    # limit 语法
    SELECT * FROM table LIMIT stratIndex,pageSize
    
    SELECT * FROM table LIMIT 5,10; // 检索记录行 6-15   
    
    
    #为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为 -1:    
    SELECT * FROM table LIMIT 95,-1; // 检索记录行 96-last.   
    
    #如果只给定一个参数,它表示返回最大的记录行数目:    
    SELECT * FROM table LIMIT 5; //检索前 5 个记录行   
     
    #换句话说,LIMIT n 等价于 LIMIT 0,n。  
    

    limit 分页实现步骤:

    1. 接口方法,需要传入两个参数:stratIndex、pageSize
    List<Student> selecLimit(Map<String, Integer> map);
    //或使用
    List<Student> selecLimit(自定义类型的对象,传入同名属性就行);
    
    1. mapper 文件
    <select id="selecLimit" resultType="Student">
        select * from student limit #{startIndex},#{pageSize}
    </select>
    
    1. 测试方法
    @Test
    public void testSelectUser() {
        
        SqlSession session = MybatisUtil.getSession();
        StudentDao dao = session.getMapper(StudentDao.class);
        
        int currentPage = 1;  //第几页
        int pageSize = 10;  //每页显示几个
        
        Map<String,Integer> map = new HashMap<String,Integer>();
        map.put("startIndex", (currentPage-1)*pageSize);
        map.put("pageSize", pageSize);
        
        List<Student> students = mapper.selecLimit(map);
    }
    

    2、分页插件PageHelper

    下载地址

    image-20200831095900149

    实现步骤:

    1. 导入 Maven 依赖
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.2.0</version>
    </dependency>
    
    1. 在 MyBatis 主配置文件中配置 <plugin> ,在 <environments> 之前添加
    <plugins>
    	<plugin interceptor="com.github.pagehelper.PageInterceptor" />
    </plugins>
    
    1. 接口方法
    List<Student> selectOnePage();
    
    1. mapper 文件
    <select id="selectOnePage" resultType="student">
        <!-- 先按年龄排个序 -->
    	select * from student order by age
    </select>
    
    1. PageHelper 对象
      查询语句之前调用 PageHelper.startPage 静态方法。
      除了 PageHelper.startPage 方法外,还提供了类似用法的 PageHelper.offsetPage 方法。
      在你需要进行分页的 MyBatis 查询方法前调用 PageHelper.startPage 静态方法即可,紧跟在这个方法后的第一个 MyBatis 查询方法会被进行分页。
    @Test
    public void testSelectOnePage() throws IOException {
        //获取第 2 页,每页 3 条内容
        PageHelper.startPage(1, 3);
        List<Student> studentList = studentDao.selectOnePage();
        studentList.forEach( stu -> System.out.println(stu));
    }
    
  • 相关阅读:
    arpg网页游戏之地图(四)
    arpg网页游戏之地图(三)
    arpg网页游戏之地图(二)
    arpg网页游戏之地图(一)
    cocos2dx三种定时器的使用以及停止schedule,scheduleUpdate,scheduleOnce。
    盖茨的几点忠告【转】
    桌面快捷方式图标都有一个蓝色的阴影
    人际关系百条细节
    需求分析的六个原则
    小细节,你做到了么?
  • 原文地址:https://www.cnblogs.com/sout-ch233/p/13608398.html
Copyright © 2020-2023  润新知