MyBatis-Plus如何分页查询?

MyBatis-Plus提供了一种简单而强大的分页查询功能,可以通过使用Page对象和Mapper接口中的方法来实现。以下是分页查询的基本步骤:

添加分页插件依赖

确保你的项目中已经添加了MyBatis-Plus的分页插件依赖。

xml 复制代码
<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-boot-starter</artifactId>
  <version>合适的版本号</version>
</dependency>

配置分页插件

在你的配置类中添加分页插件的配置。

java 复制代码
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;

@Configuration
public class MybatisPlusConfig {
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

创建Page对象

在你的服务层或控制器层,创建一个Page<T>对象,其中T是你要查询的实体类类型。

java 复制代码
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

// 第1页,每页10条数据。
Page<User> page = new Page<>(1, 10);

调用分页查询方法

如果需要自定义查询条件,可以创建一个QueryWrapper<T>对象,并在其中设置条件。

java 复制代码
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::delFlag, 0);

// 然后将其作为 selectPage 方法的第二个参数传入
Page<User> userPage = userMapper.selectPage(page, queryWrapper);

获取分页结果

selectPage方法会返回一个IPage<T>对象,其中包含了分页结果和分页信息。

java 复制代码
// 获取分页数据列表
List<User> users = userPage.getRecords();

// 获取当前页码
int current = userPage.getCurrent();

// 获取总记录数
int totalRecords = userPage.getTotal();

// 获取总页数
int pages = userPage.getPages();

// 获取每页数量
int size = userPage.getSize();

MyBatis-Plus的分页插件会自动处理SQL的LIMIT部分,你只需要关注于传递正确的参数和处理结果。分页插件还提供了对前端分页信息的支持,如totalPagespageSizetotalRecords等。

相关推荐
paopaokaka_luck3 小时前
基于Spring Boot+Vue的精品项目分享
java·vue.js·spring boot·后端·elementui·毕业设计·mybatis
ZhaiMou3 小时前
三篇文章速通JavaSE到SpringBoot框架 (下) Maven、 接口、MyBatis、Spring、SpringMVC、SpringBoot
java·spring boot·后端·spring·面试·maven·mybatis
她似晚风般温柔78910 小时前
Springboot3 + MyBatis-Plus + MySql + Vue + ProTable + TS 实现后台管理商品分类(最新教程附源码)
vue.js·mysql·mybatis
程序员大金11 小时前
基于SpringBoot+Vue+MySQL的旅游管理系统
javascript·vue.js·spring boot·后端·mysql·mybatis·旅游
大刀爱敲代码1 天前
Mybatis的基本使用
java·mybatis
计算机学姐1 天前
基于SpringBoot+Vue的留学信息推荐系统
java·vue.js·spring boot·后端·mysql·spring·mybatis
久恙5021 天前
MyBatis的注入问题
数据库·mybatis
老汉忒cpp1 天前
Redis string类型&&hash类型
java·redis·mybatis
终末圆1 天前
MyBatis—Plus 快速上手【后端 22】
java·开发语言·数据库·后端·sql·spring·mybatis