实现分页的几种方法
目录
一、简单分页查询——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);}
}