
springboot mybatis-plus 分页
发布日期:2021-05-20 02:01:45
浏览次数:17
分类:精选文章
本文共 2345 字,大约阅读时间需要 7 分钟。
MyBatis-Plus 分页配置详细指南
本文将详细说明如何在Spring Boot项目中使用 MyBatis-Plus 实现分页功能,结合实例代码进行逐步配置。
1. 安装 MyBatis-Plus 依赖
首先,我们需要在项目的 pom.xml 文件中添加相应的依赖项。
com.baomidou mybatis-plus-spring-boot-starter 1.0.5
2. 配置分页拦截器
为了实现分页功能,我们需要在 Spring Boot 项目中注册一个分页拦截器。
package com.hanhuide.driver.config;import com.baomidou.mybatisplus.plugins.PaginationInterceptor;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor page = new PaginationInterceptor(); // 设置数据库方言类型(这里设置为MySQL) page.setDialectType("mysql"); return page; }}
配置完成后,分页功能就可以在接口中使用了。
3. 创建 Mapper XML
接下来,我们需要在 mapper.xml
文件中定义分页查询方法。
4. 编写接口
在 UserMapper
接口中继承 BaseMapper
并定义分页查询方法。
public interface UserMapper extends BaseMapper { ListselectPage(Page userPage, Object o);}
5. 实现接口
在 UserService
服务类中实现上述接口:
@Overridepublic ListfindAll(Page userPage, Object o) { return userMapper.selectPage(userPage, null);}
6. 编写 Controller
在 UserController
中定义 RESTful 接口来处理分页请求。
package com.hanhuide.core.controller;import com.baomidou.mybatisplus.plugins.Page;import com.hanhuide.core.model.SysUser;import com.hanhuide.core.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController@RequestMapping("user")public class UserController { @Autowired private UserService userService; @GetMapping("/list") public Listlist(@PageUser User userPage) { Page userPageResult = new Page<>(2, 2); return userService.findAll(userPageResult, null); }}
7. 测试与验证
为了验证分页功能的实现,我们可以使用工具如 Postman 或 Swagger 测试如下 RESTful 接口:
- 请求 URL:
http://localhost:8080/user/list
- 参数:传递分页参数,如当前页和每页数量
注意事项
- 确保数据库中
sys_user
表 Already 存入数据 - 检查 SQL 语句是否正确
- 测试完成后,可以查看 respnse 中的数据总数和页信息以确保分页功能正常
通过以上步骤,您可以轻松地在 Spring Boot 项目中实现 MyBatis-Plus 分页功能,高效地管理数据库数据。
发表评论
最新留言
感谢大佬
[***.8.128.20]2025年05月07日 00时35分55秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
小程序的生命周期
2019-03-21
Redis学习笔记—单个键管理
2019-03-21
多线程基础部分
2019-03-21
Java学习记录之ArrayList集合
2019-03-21
Shiro 的身份认证
2019-03-21
什么是信道编码?信道编码比较
2019-03-21
wordpress架站踩坑过程
2019-03-21
一个简单的游戏框架[汇总]
2019-03-21
NSNotification、delegate和KVO的区别
2019-03-21
免费好用的证件扫描仪-扫描全能王
2019-03-21
自定义拦截器
2019-03-21
Kafka Producer机制优化-提高发送消息可靠性
2019-03-21
面试题5:(事务管理) ACID 是什么?
2019-03-21
ASCII码表
2019-03-21
10.Mybatis执行流程
2019-03-21
Oracle 一张表里面按照一个字段值将所有的数据按逗号拆分,变为多行数据
2019-03-21
【ucosII】4.事件管理
2019-03-21
阿里云网盘注册邀请码怎么获得,阿里云网盘注册邀请码获得内测方法
2019-03-21
Jmeter函数与变量使用详解(下)-32
2019-03-21
opencv图像处理学习(六十)——系统函数
2019-03-21