【MyBatis14】PageHelper分页插件的使用

PageHelper是适用于MyBatis框架的一个分页插件,使用方式极为便捷,支持任何复杂的单表、多表分页查询操作。

1 导入相关依赖

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>${pagehelper.version}</version>
        </dependency>

2 配置mybatis-config.xml

    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
  • com.github.pagehelper.PageInterceptor为PageHelper类所在包名

3 测试

测试方法:

        UserDao mapper = MyBatisUtil.getMapper(UserDao.class);
        PageHelper.startPage(1,2);
        List<User> users = mapper.queryAllUsers();
        for (User user : users) {
            System.out.println(user);
        }
  • PageHelper.startPage(1,2);:设置分页

    • 参数的含义是:查询第一页,每页两条数据

    • PageHelper会对其之后的第一个查询进行分页功能的追加

    • PageHelper不支持带有”for update“的查询语句

    • PageHelper不支持”嵌套查询”

测试结果:

==>  Preparing: select id,username,password,gender,regist_time from t_user LIMIT ? 
==> Parameters: 2(Integer)
......
User{id=2, username='TestUpdate1111', password='TestUpdate', gender=1, registerTime=Sun Jul 31 01:06:03 CST 2022}
User{id=3, username='Mickey', password='abc', gender=1, registerTime=Thu Apr 01 22:14:06 CST 2021}
  • 通过执行的SQL语句可以发现,分页插件实现分页的方法是通过在查询后增加LIMIT子句来实现的

PageHelper的功能强大之处不止于此,它还可以实现一些有用的分页参数的封装。

修改测试方法:

        UserDao mapper = MyBatisUtil.getMapper(UserDao.class);
        PageHelper.startPage(1,2);
        List<User> users = mapper.queryAllUsers();
        for (User user : users) {
            System.out.println(user);
        }
        PageInfo<User> pageInfo = new PageInfo(users);
        System.out.println("======================");

System.out.println("======================");处打上断点,调试执行。

通过控制台查看pageInfo对象中的属性:

通过源码查看其对应关系:

public class PageInfo<T> extends PageSerializable<T> {
    //当前页
    private int pageNum;
    //每页的数量
    private int pageSize;
    //当前页的数量
    private int size;

    //由于startRow和endRow不常用,这里说个具体的用法
    //可以在页面中"显示startRow到endRow 共size条数据"

    //当前页面第一个元素在数据库中的行号
    private int startRow;
    //当前页面最后一个元素在数据库中的行号
    private int endRow;
    //总页数
    private int pages;

    //前一页
    private int prePage;
    //下一页
    private int nextPage;

    //是否为第一页
    private boolean isFirstPage = false;
    //是否为最后一页
    private boolean isLastPage = false;
    //是否有前一页
    private boolean hasPreviousPage = false;
    //是否有下一页
    private boolean hasNextPage = false;
    //导航页码数
    private int navigatePages;
    //所有导航页号
    private int[] navigatepageNums;
    //导航条上的第一页
    private int navigateFirstPage;
    //导航条上的最后一页
    private int navigateLastPage;
    ......

4 分页练习

通过Servlet+JSP+MyBatis搭建一个简单的分页demo

entity:

public class User implements Serializable {
    private Integer id;
    private String username;
    private String password;
    private Integer gender;
    private Date registerTime;

    public User() {
    }
    ......

dao:

public interface UserDao {
    List<User> queryAllUsers();
}

DAOMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jackqiang.dao.UserDao">
    <cache/>
    <resultMap id="user_resultMap" type="User">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <result column="gender" property="gender"/>
        <result column="regist_time" property="registerTime"/>
    </resultMap>
    <sql id="user_field">
        select id,username,password,gender,regist_time
        from t_user
    </sql>
    <select id="queryAllUsers" resultMap="user_resultMap">
        <include refid="user_field"/>
    </select>
</mapper>

service:

public interface UserService {
    PageInfo<User> queryAllUsersByPage(Page page);
}

service.Impl:

public class UserServiceImpl implements UserService {
    @Override
    public PageInfo<User> queryAllUsersByPage(Page page) {
        UserDao mapper = MyBatisUtil.getMapper(UserDao.class);
        PageHelper.startPage(page.getPageNum(),page.getPageSize());
        List<User> users = mapper.queryAllUsers();
        return new PageInfo<User>(users);
    }
}

 controller:

@WebServlet("/users")
public class UserController extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        String pageNum = req.getParameter("pageNum");
        String pageSize = req.getParameter("pageSize");
        Page page = new Page();
        if (pageNum != null) {
            page.setPageNum(Integer.parseInt(pageNum));
        }
        if (pageSize != null) {
            page.setPageSize(Integer.parseInt(pageSize));
        }
        PageInfo<User> pageData = userService.queryAllUsersByPage(page);
        req.setAttribute("pageData", pageData);
        req.getRequestDispatcher("/users.jsp").forward(req, res);
    }
}

jsp:

<%--
  Created by IntelliJ IDEA.
  User: qiang
  Date: 2022/7/31
  Time: 20:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <table width="500px" align="center" border="1px" cellspacing="0">
        <tr>
            <th>id</th>
            <th>username</th>
            <th>password</th>
            <th>gender</th>
            <th>registerTime</th>
        </tr>
        <c:forEach items="${requestScope.pageData.list}" var="user">
            <tr>
                <td>${user.id}</td>
                <td>${user.username}</td>
                <td>${user.password}</td>
                <td>${user.gender}</td>
                <td>${user.registerTime}</td>
            </tr>
        </c:forEach>
    </table>
    <div style="text-align: center">
        <a href="${pageContext.request.contextPath}/users?pageNum=1&pageSize=2">首页</a>
        <c:if test="${requestScope.pageData.hasPreviousPage}">
            <a href="${pageContext.request.contextPath}/users?pageNum=${requestScope.pageData.prePage}&pageSize=2">上一页</a>
        </c:if>
        <c:forEach begin="1" end="${requestScope.pageData.pages}" var="i">
            <a href="${pageContext.request.contextPath}/users?pageNum=${i}&pageSize=2">
                <c:if test="${requestScope.pageData.pageNum == i}">
                    <span style="color: red">${i}</span>
                </c:if>
                <c:if test="${requestScope.pageData.pageNum != i}">
                    <span>${i}</span>
                </c:if>
            </a>
        </c:forEach>
        <c:if test="${requestScope.pageData.hasNextPage}">
            <a href="${pageContext.request.contextPath}/users?pageNum=${requestScope.pageData.nextPage}&pageSize=2">下一页</a>
        </c:if>
        <a href="${pageContext.request.contextPath}/users?pageNum=${requestScope.pageData.pages}&pageSize=2">末页</a>
    </div>
</body>
</html>

最终效果:

 

版权声明:
作者:jackqiang
链接:http://www.jackqiang.com/framework/mybatis/1954/pagehelper/
来源:JackQiang's
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>
文章目录
关闭
目 录