POM依赖
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.2.0</version> </dependency>
Mybatis配置文件
<plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <property name="helperDialect" value="mysql"/> </plugin> </plugins>
Servlet代码示例
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String page = request.getParameter("page"); String size = request.getParameter("size"); StudentService studentService = new StudentServiceImpl(); PageHelper.startPage(page == null ? 1:Integer.parseInt(page),size == null ? 4:Integer.parseInt(size)); List<Student> list = studentService.findAllStudent(); PageInfo pageInfo = PageInfo.of(list); response.getWriter().println(new ObjectMapper().writeValueAsString(pageInfo)); }
1、PageHelper的优点是,分页和Mapper.xml完全解耦。实现方式是以插件的形式,对Mybatis执行的流程进行了强化,添加了总数count和limit查询。属于物理分页。
2、Page page = PageHelper.startPage(pageNum, pageSize, true); - true表示需要统计总数,这样会多进行一次请求select count(0); 省略掉true参数只返回分页数据。
参考:
https://www.cnblogs.com/kangoroo/p/7998433.html