Mybatis-plus的分页查询

时间:2025-04-11 19:18:54

Mybatis-plus的分页查询

    • 1. 简单说明
    • 2. 介绍说明
    • 3. 完整配置类代码:
    • 4. 示例代码
    • 5. 最后总结

1. 简单说明

嗨,大家好!今天给大家分享的是Mybatis-plus 插件的分页机制,说起分页机制,相信我们程序员都不陌生,今天,我就给大家分享一下Mybatis-plus的分页机制,供大家学习和Copy。

2. 介绍说明

如果你想看代码,可以直接跳到代码区域,这里只是一些简单的说明,如果你想学习,建议可以看看这一块的任容

本章节将介绍 BaseMapper 中的分页查询,BaseMapper 接口提供了如下几个分页查询接口:

  • selectPage:根据 entity 条件,查询全部记录
  • selectMapsPage:根据 Wrapper 条件,查询全部记录

在使用上面两个方法进行分页查询时,我们需要配置分页插件。这是只是在介绍SpringBoot的使用。
注意:由于我们使用的 Spring Boot 项目,因此需要通过 @Configuration@Bean 注解来添加配置

3. 完整配置类代码:

下边就是完整的配置类,至于为什么比官网上的少一点,因为那个可以说会报错,而且也不需要使用到它,以下就是完整配置类:

package .mybatis_plus;
 
import ;
import ;
import ;
import ;
import ;
 
@Configuration
public class MybatisPlusConfig {
 
    /**
     * 分页插件。如果你不配置,分页插件将不生效
     */
    @Bean
    public MybatisPlusInterceptor paginationInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 指定数据库方言为 MYSQL
        (new PaginationInnerInterceptor());
        return interceptor;
    }
 
}

注意:如果你没有配置分页插件,则不会进行分页。所以这个一定要配置。

4. 示例代码

  1. 使用 QueryWrapper 和 Page 作为参数进行分页,例如:

    package .mybatis_plus.select;

    import ;
    import ;
    import ;
    import .mybatis_plus.;
    import .mybatis_plus.;
    import ;
    import ;
    import ;
    import ;
    import .;

    @RunWith()
    @SpringBootTest
    class Select6Test {

    @Autowired
    private SimpleMapper simpleMapper;

    @Test
    void contextLoads() {
    QueryWrapper wrapper = new QueryWrapper<>();
    (“user_id”);

       // 创建分页对象(1表示第一页;4表示每页大小为4)
       Page<UserBean> page = new Page<>(1, 4);
       Page<UserBean> result = (page, wrapper);
       ("page == result: " + (page == result));
       ("size: " + ());
       ("total: " + ());
       for(UserBean userBean : ()) {
           (userBean);
       }
    

    }

    }

运行上面代码,你会发现 page 和selectPage 返回的 result1 相等,说明两者是同一个对象。因此,可以忽略掉 selectPage 方法的返回结果,如下:

Page<UserBean> page = new Page<>(1, 4);
(page, wrapper);
  1. 另外一个分页方法,selectMapsPage 和上面的使用方法一样,仅仅是返回类型不一样。代码如下:

    package .mybatis_plus.select;

    import ;
    import .mybatis_plus.;
    import ;
    import ;
    import ;
    import ;
    import .;
    import ;

    @RunWith()
    @SpringBootTest
    class Select7Test {

    @Autowired
    private SimpleMapper simpleMapper;
    
    @Test
    void contextLoads() {
        // 返回的结果类型为 Map<String,Object>
        Page<Map<String,Object>> page = new Page<>(1, 4);
        (page, null);
        ("size: " + ());
        ("total: " + ());
        ("pages: " + ());
        for(Map<String,Object> map : ()) {
            (map);
        }
    }
    

    }

注意:这里我们平常会使用以下代码获取page里边的存放的代码。
():这是用来获取我们分页查出来的数据

5. 最后总结

这一小结,我们主要是对mybatis-pluts 插件的分页功能的使用,做了简单介绍。下边我们来梳理以下,使用插件步骤:

  1. 在我们项目的配置文件夹下,一定要添加MybatisPlusConfig
  2. 我们需要在这个配置类中添加paginationInterceptor()方法,进行分页功能的配置,其实就是配置分页功能的拦截器
  3. 使用方法,进来数据的分页
  4. 使用方法,返回分页的数据

以上就是我们使用分页的步骤了,这里需要注意一些问题,一定要把相应的注解加上去,要不然,是没办法使用的。