一、mysql
前端请求参数包括page_num和page_size, 首先对这两个参数进行合法性判断,然后重新计算下page_num,让当前page_num对应的就是你要定位到的第n条数据,比如现在要查看第6页数据,且page_size=7,那也就是要获取到第37行-43行数据。
复习下mysql中limit的使用:
LIMIT 子句可以被用于强制 SELECT 语句返回指定的记录数。LIMIT 接受一个或两个数字参数。参数必须是一个整数常量。如果给定两个参数,第一个参数指定第一个返回记录行的偏移量,第二个参数指定返回记录行的最大数目。初始记录行的偏移量是 0(而不是 1)。
所以,对于上述情况,对应的偏移量=(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);
.xml中sql语句示例:
<select id="getExampleByPage" resultMap="AllExampleInfo">
select *
from Example
limit #{page},#{size}
</select>
二、Pagehelper
PageHelper做数据分页,在你的select语句后面加入分页的sql内容,如果你使用的mysql数据库,它就是在select * from student 后面加入limit语句。
使用步骤:
-
加入依赖pagehelper依赖
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.10</version> </dependency>
-
在mybatis主配置文件,加入plugin声明
在<environments>之前加入 <plugins> <plugin interceptor ="com.github.pagehelper.PageInterceptor"/> </plugins>
-
在select语句之前,调用PageHelper.startPage(页码,每页大小)
@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(); }