使用mybatis-plus如何实现分页查询功能

本文介绍如何使用MyBatis-Plus实现分页查询功能,包括引入依赖、配置数据源、创建实体类和Mapper接口等步骤,并通过示例演示了如何进行分页查询。

今天就跟大家聊聊有关使用mybatis-plus如何实现分页查询功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

引入依赖:

<!-- 引入mybatisPlus -->
    <dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-boot-starter</artifactId>
   <version>3.2.0</version>
  </dependency>
  <!-- 引入mysql驱动包 -->
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.27</version>
  </dependency>
  <!-- 引入Druid依赖,阿里巴巴所提供的数据源 -->
  <dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid</artifactId>
   <version>1.0.29</version>
    </dependency>

在application.yml配置

spring:
 datasource:
 type: com.alibaba.druid.pool.DruidDataSource
 driver-class-name: com.mysql.jdbc.Driver
 url: jdbc:mysql://127.0.0.1:3306/test&#63;useUnicode=true&characterEncoding=UTF-8
 username: root
 password: 123456

在启动类上面添加@MapperScan注解,扫描mapper包

@SpringBootApplication
@MapperScan("com.qiao.demo02.mapper")
public class SpringbootDemo02Application {

 public static void main(String[] args) {
  SpringApplication.run(SpringbootDemo02Application.class, args);
 }

}

新建User和UserMapper
在这里插入图片描述

user类

@Data
public class User {
 @TableId
 private Integer userId;
 private String userName;
 private Integer userAge;
 private String userEmail;
}
UserMapper接口
 public interface UserMapper extends BaseMapper<User> {
 
 }

最重要的是继承BaseMapper接口:里面声明了很强大的CRUD方法

public interface BaseMapper<T> extends Mapper<T> {
 int insert(T entity);

 int deleteById(Serializable id);

 int deleteByMap(@Param("cm") Map<String, Object> columnMap);

 int delete(@Param("ew") Wrapper<T> wrapper);

 int deleteBatchIds(@Param("coll") Collection<&#63; extends Serializable> idList);

 int updateById(@Param("et") T entity);

 int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);

 T selectById(Serializable id);

 List<T> selectBatchIds(@Param("coll") Collection<&#63; extends Serializable> idList);

 List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);

 T selectOne(@Param("ew") Wrapper<T> queryWrapper);

 Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);

 List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);

 List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);

 List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);

 IPage<T> selectPage(IPage<T> page, @Param("ew") Wrapper<T> queryWrapper);

 IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param("ew") Wrapper<T> queryWrapper);
}

分页查询

这点官方文档讲的也很详细:https://mp.baomidou.com/guide/page.html

新建一个config包,在里面建一个MybatisPlus配置类 返回一个分页拦截器

package com.qiao.demo02.config;

@Configuration
@ConditionalOnClass(value = {PaginationInterceptor.class})
public class MybatisPlusConfig {
 @Bean
 public PaginationInterceptor paginationInterceptor() {
  PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
  return paginationInterceptor;
 }
}

这样就能使用mybatis的分页功能了

Junit测试

@Resource
 private UserMapper userMapper;
 @Test
 public void queryUserForPage(){
  IPage<User> userPage = new Page<>(2, 2);//参数一是当前页,参数二是每页个数
  userPage = userMapper.selectPage(userPage, null);
  List<User> list = userPage.getRecords();
  for(User user : list){
   System.out.println(user);
  }
 }

Controller返回json串

先定义一个包装类UserVo,用来保存分页所需要的数据

package com.qiao.demo02.vo;

@Data
public class UserVo {
 private Integer current;
 private Integer size;
 private Long total;
 private List<User> userList;
}

然后在控制器编写代码,这里省略了service层,实际开发业务代码写在service层,Controller只负责:接受参数、调用service层方法处理业务逻辑,返回结果

Controller类贴上了@RestController注解

 @GetMapping("queryUser")
 public UserVo queryList(Integer current, Integer size) {
  /**
   * 这些代码应该写在service层
   */
  UserVo userVo = new UserVo();
  IPage<User> page = new Page<>(current, size);
  userMapper.selectPage(page, null);
  userVo.setCurrent(current);
  userVo.setSize(size);
  userVo.setTotal(page.getTotal());
  userVo.setUserList(page.getRecords());
  return userVo;
 }

附上结果,前端直接处理json数据即可
在这里插入图片描述
看完上述内容,你们对使用mybatis-plus如何实现分页查询功能有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注小编,感谢大家的支持。

<think> 首先,用户的问题是:“我想查找Mybatis-plus实现分页查询的方式 请问Mybatis-plus实现分页查询的方法”。用户想了解Mybatis-plus实现分页查询的方法。 我有系统级指令: - 所有行内数学表达式使用$...$格式。 - 独立公式使用$$...$$并单独成段。 - LaTeX语法正确。 - 使用中文回答。 - 生成相关问题。 - 回答中引用的段落末尾自然地添加引用标识,例如[^1]。 用户还提供了几个引用: - [1]: 关于MyBatis-Plus分页封装的深度解析。 - [2]: Mybatis-plus分页查询的介绍。 - [3]: MyBatis-Plus实现分页查询的解释,包括分页插件和自动分页。 - [4]: 一个小例子,前端和后端实现分页。 - [5]: mybatis-plus 3.5.12版本的分页查询实现代码示例。 我需要参考这些引用来回答问题。用户说“上述引用仅供参考”,但我应该尽可能地参考用户上一次的问题和我的回答。用户是针对这个查询提问的。 结构化回答: - 我需要逐步解释Mybatis-plus实现分页查询的方法。 - 确保回答清晰、可靠。 - 在结尾生成相关问题。 - 引用时添加引用标识。 关键点从引用中提取: - 引用[3]: MyBatis-Plus使用分页插件(PaginationInterceptor)和自动分页功能,通过拦截器自动处理分页。 - 引用[5]: 提供了一个代码示例:使用Page类和QueryWrapper来实现分页查询- 其他引用提供概述和案例。 Mybatis-plus实现分页查询的核心方法是: 1. 添加分页插件(在Spring Boot应用中配置Interceptor)。 2. 在Mapper接口中定义方法,返回Page对象。 3. 使用Page类创建分页参数。 4. 使用QueryWrapper添加查询条件。 步骤分解: 1. **配置分页插件**:在Spring Boot中,添加一个配置类来启用分页插件。 2. **定义Mapper方法**:在Mapper接口中,使用selectPage方法或其他支持分页的方法。 3. **在Service调用**:创建Page对象,指定页码和大小,调用Mapper方法。 4. **处理结果**:Page对象包含分页信息和数据列表。 从引用[5]的代码: ```java public Page<Notice> selectPage(Integer pageNum, Integer pageSize, String title) { Page<Notice> page = new Page<>(pageNum, pageSize); QueryWrapper<Notice> queryWrapper = new QueryWrapper<>(); if (!"".equals(title)) { queryWrapper.like("title", title); } return noticeMapper.selectPage(page, queryWrapper); } ``` 回答结构: - 开头简介:解释Mybatis-plus分页查询的基本概念。 - 详细步骤:分步骤说明。 - 代码示例:提供简单的代码片段。 - 结尾生成相关问题。 确保中文回答。 生成相关问题:基于主题,如: 1. 如何配置Mybatis-plus的分页插件? 2. Mybatis-plus分页查询的性能优化? 3. Mybatis-plus分页与其他框架的区别? 4. 在实际项目中应用分页查询的案例? 引用添加: - 当提到引用内容时,在末尾添加[^n]。 - 例如,引用[3]解释自动分页,添加[^3]. 最终回答大纲: 1. 引言:简述Mybatis-plus分页查询。 2. 实现方法步骤: - 第一步:配置分页插件。 - 第二步:定义Mapper方法。 - 第三步:在Service层调用。 - 第四步:前端处理(可选)。 3. 代码示例(简化)。 4. 优缺点或注意事项。 5. 相关问题。 </think> ### Mybatis-Plus 实现分页查询的方法 Mybatis-Plus 是一个强大的 MyBatis 增强工具,它通过简化分页查询实现,提升了开发效率。分页查询的核心依赖于 **分页插件(PaginationInterceptor)**,该插件自动拦截 SQL 请求并添加分页逻辑(如 `LIMIT` 和 `OFFSET`),无需手动编写复杂的分页代码[^3]。下面我将一步步解释实现方法,确保结构清晰可靠。 #### 1. **配置分页插件(后端设置)** - Mybatis-Plus 的分页功能需通过插件启用。在 Spring Boot 项目中,添加一个配置类来注册分页拦截器。 - **示例配置代码**: ```java import com.baomidou.mybatisplus.annotation.DbType; 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 { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // 添加分页插件,指定数据库类型(如 MySQL) interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } } ``` - 此配置类确保所有 Mapper 查询自动支持分页,拦截器会在 SQL 执行前注入分页参数[^3][^5]。 #### 2. **定义 Mapper 方法(数据层)** - 在 Mapper 接口中,直接使用 Mybatis-Plus 提供的 `selectPage` 方法,该方法接收一个 `Page` 对象作为分页参数。 - **Mapper 接口示例**: ```java import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.ibatis.annotations.Mapper; @Mapper public interface NoticeMapper extends BaseMapper<Notice> { // 分页查询方法:Page 对象封装页码(pageNum)和每页大小(pageSize) Page<Notice> selectPage(Page<Notice> page, QueryWrapper<Notice> queryWrapper); } ``` - 这里 `Page` 类是 Mybatis-Plus 的核心分页对象,自动处理分页计算[^5][^3]。 #### 3. **在 Service 层调用分页方法(业务逻辑)** - 在 Service 实现中,创建 `Page` 对象并传递查询条件(使用 `QueryWrapper`),然后调用 Mapper 的分页方法。 - **Service 实现示例**: ```java import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.springframework.stereotype.Service; @Service public class NoticeService { private final NoticeMapper noticeMapper; public NoticeService(NoticeMapper noticeMapper) { this.noticeMapper = noticeMapper; } public Page<Notice> getNoticePage(Integer pageNum, Integer pageSize, String title) { // 创建分页对象:pageNum 为当前页码,pageSize 为每页记录数 Page<Notice> page = new Page<>(pageNum, pageSize); // 构建查询条件(可选) QueryWrapper<Notice> queryWrapper = new QueryWrapper<>(); if (title != null && !title.isEmpty()) { queryWrapper.like("title", title); // 添加模糊查询条件 } // 执行分页查询 return noticeMapper.selectPage(page, queryWrapper); } } ``` - **返回值**:`Page<Notice>` 对象包含: - `page.getRecords()`:当前页的数据列表。 - `page.getTotal()`:总记录数。 - `page.getPages()`:总页数。 - 此方法实现了自动分页,无需在 SQL 中显式编写 `LIMIT`[^3][^5][^1]。 #### 4. **前端整合(可选,用于完整流程)** - 前端(如 Vue + ElementUI)通过 API 获取分页数据,并使用分页组件渲染。例如: - 前端发送请求:`GET /notices?pageNum=1&pageSize=10&title=test` - 后端 Controller 调用 Service 方法返回分页数据。 - 引用[^4]提供了一个前后端集成的完整案例,确保数据一致性[^4]。 #### 关键注意事项 - **优点**:代码简洁,复用性高;支持动态查询条件;自动处理分页逻辑,减少错误[^1][^2]。 - **缺点**:在大数据量下需优化性能(如索引设计);分页插件可能对复杂 SQL 产生兼容性问题[^3]。 - **最佳实践**:始终使用 `QueryWrapper` 添加条件,避免 SQL 注入;测试分页边界用例(如 pageNum=0 或超大 pageSize)[^5][^1]。 通过以上步骤,Mybatis-Plus 简化了分页查询实现,开发者只需关注业务逻辑,分页细节由框架自动处理[^3][^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TensorFlowcv

感谢老板打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值