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;
@Configuration
public 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 {
List
selectPage(Page
userPage, Object o);
}

5. 实现接口

UserService 服务类中实现上述接口:

@Override
public List
findAll(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 List
list(@PageUser User userPage) {
Page
userPageResult = new Page<>(2, 2);
return userService.findAll(userPageResult, null);
}
}

7. 测试与验证

为了验证分页功能的实现,我们可以使用工具如 Postman 或 Swagger 测试如下 RESTful 接口:

  • 请求 URLhttp://localhost:8080/user/list
  • 参数:传递分页参数,如当前页和每页数量

注意事项

  • 确保数据库中 sys_user 表 Already 存入数据
  • 检查 SQL 语句是否正确
  • 测试完成后,可以查看 respnse 中的数据总数和页信息以确保分页功能正常

通过以上步骤,您可以轻松地在 Spring Boot 项目中实现 MyBatis-Plus 分页功能,高效地管理数据库数据。

上一篇:springboot 多数据源添加事务管理
下一篇:vue 权限管理 主题切换(8)

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年05月07日 00时35分55秒