当前位置: 首页 > news >正文

实现分页的几种方法

目录

一、简单分页查询——limit

1 基于注解的简单分页查询

2 基于Mapper.xml的复杂分页

二、PageHelper

三、基于mp实现分页


一、简单分页查询——limit

1 基于注解的简单分页查询

Mapper接口

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;public interface UserMapper {// 分页查询用户@Select("SELECT * FROM user LIMIT #{offset}, #{limit}")List<User> selectByPage(@Param("offset") int offset, @Param("limit") int limit);// 查询总记录数@Select("SELECT COUNT(*) FROM user")int getTotalCount();
}

Service类

public class UserService {@Autowiredprivate UserMapper userMapper;public Page<User> getPage(int currentPage, int pageSize) {int total = userMapper.getTotalCount(); // 获取总记录数int totalPage = (total + pageSize - 1) / pageSize; // 计算总页数int offset = (currentPage - 1) * pageSize; // 计算偏移量List<User> users = userMapper.selectByPage(offset, pageSize); // 获取分页数据return new Page<>(currentPage, pageSize, total, totalPage, users);}
}

Controller类

Page<User> page = userService.getPage(1, 10); // 获取第 1 页,每页 10 条记录

2 基于Mapper.xml的复杂分页

(1)定义Page类——封装分页结果

public class Page {private int currentPage; // 当前页码private int pageSize; // 每页显示的记录数// 构造方法public Page(int currentPage, int pageSize) {this.currentPage = currentPage;this.pageSize = pageSize;
}// 计算偏移量public int getOffset() {return (currentPage - 1) * pageSize;}
}

(2)定义PageResult类——封装查询结果

import java.util.List;public class PageResult<T> {private List<T> data; // 分页数据private int total; // 总记录数private int totalPage; // 总页数private int currentPage; // 当前页码private int pageSize; // 每页显示的记录数// 构造方法public PageResult(List<T> data, int total, int currentPage, int pageSize) {this.data = data;this.total = total;this.currentPage = currentPage;this.pageSize = pageSize;this.totalPage = (total + pageSize - 1) / pageSize; // 计算总页数}}

(3)Mapper接口

import org.apache.ibatis.annotations.Param;
import java.util.List;public interface UserMapper {// 分页查询用户List<User> selectByPage(@Param("condition") String condition, @Param("offset") int offset, @Param("limit") int limit);// 查询总记录数int getTotalCount(@Param("condition") String condition);
}

(4)xxxMapper.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.example.mapper.UserMapper"><!-- 分页查询 --><select id="selectByPage" resultType="User">SELECT * FROM userWHERE name LIKE CONCAT('%', #{condition}, '%')LIMIT #{offset}, #{limit}</select><!-- 查询总记录数 --><select id="getTotalCount" resultType="int">SELECT COUNT(*) FROM userWHERE name LIKE CONCAT('%', #{condition}, '%')</select></mapper>

(5)Service层

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class UserService {@Autowiredprivate UserMapper userMapper;// 获取分页数据public PageResult<User> getPage(String condition, Page page) {// 查询总记录数int total = userMapper.getTotalCount(condition);// 查询分页数据List<User> users = userMapper.selectByPage(condition, page.getOffset(), page.getPageSize());// 封装分页结果return new PageResult<>(users, total, page.getCurrentPage(), page.getPageSize());}
}

(6)Controller

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
public class UserController {@Autowiredprivate UserService userService;@GetMapping("/users")public PageResult<User> getUsers(@RequestParam String condition,@RequestParam int currentPage,@RequestParam int pageSize) {Page page = new Page(currentPage, pageSize); // 创建分页对象return userService.getPage(condition, page); // 调用 Service 层方法}
}

二、PageHelper

(1)引入依赖

<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.2.0</version>
</dependency>

(2)配置 MyBatis

在 mybatis-config.xml 中配置 PageHelper 插件:

<configuration><plugins><plugin interceptor="com.github.pagehelper.PageHelper"><property name="helperDialect" value="mysql"/>  <!-- 配置数据库方言 --><property name="reasonable" value="true"/><property name="supportMethodsArguments" value="true"/></plugin></plugins>
</configuration>

(4)使用PageHelper实现分页

无查询条件:

Mapper接口:

import com.github.pagehelper.Page;
import org.apache.ibatis.annotations.Select;import java.util.List;public interface UserMapper {@Select("SELECT id, username, age FROM user")Page<User> getAllUsers();  // 返回 Page 类型,PageHelper 会自动处理分页
}

Service层:

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;@Service
public class UserService {@Autowiredprivate UserMapper userMapper;public PageInfo<User> getUsersByPage(int pageNum, int pageSize) {// 使用 PageHelper.startPage 开始分页PageHelper.startPage(pageNum, pageSize);// 查询数据List<User> userList = userMapper.getAllUsers();// 使用 PageInfo 包装查询结果,返回分页信息return new PageInfo<>(userList);}
}

Controller层:

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
public class UserController {@Autowiredprivate UserService userService;@GetMapping("/users")public PageInfo<User> getUsers(@RequestParam int pageNum, @RequestParam int pageSize) {return userService.getUsersByPage(pageNum, pageSize);}
}

有查询条件:

public interface UserMapper {List<User> selectAll(@Param("condition") String condition);
}
<?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.example.mapper.UserMapper"><select id="selectAll" resultType="User">SELECT * FROM userWHERE name LIKE CONCAT('%', #{condition}, '%')</select></mapper>
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;public class UserService {@Autowiredprivate UserMapper userMapper;public PageInfo<User> getPage(String condition, int currentPage, int pageSize) {// 使用 PageHelper 插件开始分页PageHelper.startPage(currentPage, pageSize);// 调用 Mapper 方法查询数据List<User> users = userMapper.selectAll(condition);// 使用 PageInfo 封装分页信息return new PageInfo<>(users);}
}

 在控制器或其他地方调用分页方法,传入查询条件、当前页码和每页显示的记录数。

PageInfo<User> pageInfo = userService.getPage("张三", 1, 10); // 查询条件为 "张三",获取第 1 页,每页 10 条记录
List<User> users = pageInfo.getList(); // 获取分页数据
int total = (int) pageInfo.getTotal(); // 获取总记录数
int pages = pageInfo.getPages(); // 获取总页数

三、基于mp实现分页

(1)在项目的 pom.xml 文件中添加 MyBatis-Plus 的依赖。如果你已经使用了 MyBatis-Plus,则可以跳过这一步。

(2) 配置分页插件

在 MyBatis-Plus 的配置类中,配置分页插件 PaginationInterceptor

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class MyBatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor());return interceptor;}
}

(3)定义 Mapper 接口

 在 MyBatis-Plus 中,Mapper 接口继承自 BaseMapper,并可以使用 BaseMapper 提供的分页查询方法。

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entity.User;public interface UserMapper extends BaseMapper<User> {// MyBatis-Plus 的 BaseMapper 已经提供了分页查询方法,无需额外定义
}

(4)实现Service层

在 Service 层中,使用 MyBatis-Plus 提供的分页查询方法。

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;@Service
public class UserService extends ServiceImpl<UserMapper, User> {// 使用 MyBatis-Plus 的分页查询方法public IPage<User> getPage(Page<User> page, String condition) {// 使用条件构造器构建查询条件QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.like("name", condition);// 调用 MyBatis-Plus 的分页查询方法return userMapper.selectPage(page, queryWrapper);}
}

(5)Controller层

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
public class UserController {@Autowiredprivate UserService userService;@GetMapping("/users")public IPage<User> getUsers(@RequestParam String condition,@RequestParam int current,@RequestParam int size) {// 创建分页对象Page<User> page = new Page<>(current, size);// 调用 Service 层方法return userService.getPage(page, condition);}
}

相关文章:

  • Field访问对象int字段,对象访问int字段,通过openjdk17 C++源码看对象字段访问原理
  • 97AB-ASEMI机器人功率器件专用97AB
  • 模型上下文协议(MCP)深度解析:大模型从“思考者“进化为“行动者“
  • 01 C++概述
  • 2025 SAP专精特新企业高峰论坛 | 工博科技以SAP公有云+AI赋能新质生产力​
  • 15、项目搭建:绘制城堡蓝图——React 19 工程配置
  • 在android 系统上qnn sdk转换,运行模型示例
  • Shell脚本-嵌套循环应用案例
  • 塔能科技:点亮节能之光,赋能工厂与城市
  • 013几何数学——算法备赛
  • 科技助力防灾减灾:卫星电话走进应急救援队伍
  • Python创意爱心代码分享指南
  • ​LangChain、LlamaIndex、MCP、Spring AI、Ollama​ 和 ​DeepSeek​ 的定义、关系及典型架构设计
  • 完美解决.NET Framework 4.0 中 System.Drawing 库不支持 WebP 格式的图像处理
  • Docker 获取 Python 镜像操作指南
  • Dots:动态实现GPUECSAnimationBaker的受击变红效果
  • 不同参数大小的DeepSeekR1模型对Java中new FileInputStream(“test.txt“).seek(100);语法错误的检查
  • WPF之Button控件详解
  • Golang|外观模式和具体逻辑
  • 【杂谈】-人工智能驱动的网络安全威胁:新一代网络钓鱼
  • 西湖大学本科招生新增三省两市,首次面向上海招生
  • 走访中广核风电基地:701台风机如何乘风化电,点亮3000万人绿色生活
  • 日本大米价格连续16周上涨,再创最高纪录
  • 野猪穿过江苏电视台楼前广场,被抓捕后送往红山森林动物园
  • 马上评丨发钱奖励结婚,支持婚育就该系统性发力
  • 大漠孤烟为何“直”?物理学家在唐诗中读出“不一样的美”