Several ways of Spring paging

1. The mysql
front-end request parameters include page_num and page_size. First, judge the legality of these two parameters, and then recalculate the page_num, so that the current page_num corresponds to the nth data you want to locate. For example, now you want to check the 6th Page data, and page_size=7, that is to get the data of the 37th-43rd row.
Review the use of limit in mysql:
The LIMIT clause can be used to force the SELECT statement to return a specified number of records. LIMIT accepts one or two numeric arguments. The argument must be an integer constant. If two parameters are given, the first parameter specifies the offset of the first returned record row, and the second parameter specifies the maximum number of returned record rows. The offset of the initial record line is 0 (instead of 1).
So, for the above case, the corresponding offset=(7-1)*6=36.

if (page_num != null && page_size != null) {
    page_num = (page_num - 1) * page_size;
}
List<Example> data = exampleMapper.getExample(page_num, page_size);



Example of sql statement in .xml:

<select id="getExampleByPage" resultMap="AllExampleInfo">
        select * 
        from Example
        limit #{page},#{size}
</select>

Two, Pagehelper

PageHelper does data paging, and adds paging sql content after your select statement. If you use a mysql database, it adds a limit statement after select * from student.

Steps for usage:

  1. Add dependency pagehelper dependency

    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.10</version>
    </dependency>
  2. In the main configuration file of mybatis, add the plugin statement

    
    Add <plugins> before <environments> 
        <plugin interceptor ="com.github.pagehelper.PageInterceptor"/> 
    </plugins>
  3. Before the select statement, call PageHelper.startPage(page number, size of each page)

    @Test
    public void testPageHelper(){
        //1.获取SqlSession对象
        SqlSession session = MybatisUtil.getSqlSession();
        //2.获取dao的代理
        StudentDao dao =session.getMapper(StudentDao.class);
    ​
       //调用PageHelper的方法
        PageHelper.startPage(1,3);
        List<Student> students = dao.selectAllStudents();
    ​
        students.forEach(stu -> System.out.println("stu="+stu) );
        //4.关闭
        session.close();
    ​
    ​
    }

Guess you like

Origin blog.csdn.net/weixin_53630942/article/details/124215958