MyBatis-plus 提供了 Page 类来实现分页功能,使用方法如下:

  1. 在 Mapper 接口中定义分页方法,方法参数中需要包含 Page 对象。
List<User> selectUserPage(Page<User> page, @Param("name") String name);
  1. 在 Mapper XML 文件中编写 SQL 语句,使用分页插件进行分页。
<select id="selectUserPage" resultType="User">
    select * from user where name like concat('%', #{name}, '%')
    <if test="page != null">
        limit #{page.offset}, #{page.size}
    </if>
</select>
  1. 在 Service 层调用 Mapper 方法,传入 Page 对象。
Page<User> page = new Page<>(1, 10);
List<User> userList = userService.selectUserPage(page, "张三");

其中,Page 的构造函数需要传入当前页码和每页记录数,调用 selectUserPage 方法时,需要传入 Page 对象和查询条件参数。

在 Mapper XML 文件中,使用了 if 标签判断是否传入了 Page 对象,在传入了 Page 对象时,使用 limit 关键字进行分页。Page 对象中的 offset 和 size 属性分别表示当前页的起始记录索引和每页的记录数。

使用 MyBatis-plus 的 Page 类可以方便地实现分页功能,避免了手动计算分页参数的繁琐操作。

MyBatis-Plus 分页功能实现教程:简单易懂的示例

原文地址: https://www.cveoy.top/t/topic/jkGq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录