MyBatisPlus提供的分页功能

会当凌绝顶,一览众山小

| @Author:

MyBatisPlus框架系列文章目录:

    MyBatisPlus提供的分页功能(当前) [MyBatisPlus之代码生成器(近期发布)]

前言

本文介绍了如何使用MybatisPlus提供的分页功能

编写配置类,启动分页插件

在使用分页功能前,需要编写MybatisPlus的配置类,来启用分页插件

package com.example.config;

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();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

测试BaseMapper提供的selectPage方法

@Test
    public void testSelectPage(){
          
   
        Page<User> page1 = new Page<>(1, 3);
        // 第二个参数Wrapper为null,表示没有where子句,即查询表中所有的记录
        Page<User> userPage1 = userMapper.selectPage(page1, null);
        userPage1.getRecords().forEach(System.out::println);

        Page<User> page2 = new Page<>(2, 3);
        Page<User> userPage2 = userMapper.selectPage(page2, null);
        userPage2.getRecords().forEach(System.out::println);
    }

生成的sql语句及输出

==>  Preparing: SELECT COUNT(1) FROM user
==> Parameters: 
<==      Total: 1
==>  Preparing: SELECT id,name,age,gender,email FROM user LIMIT ?
==> Parameters: 3(Long)
<==      Total: 3
User(id=1, name=Alice, age=17, gender=0, email=alice@gmail.com)
User(id=2, name=Bob, age=19, gender=1, email=bob@gmail.com)
User(id=3, name=Colin, age=13, gender=1, email=colin@gmail.com)
==>  Preparing: SELECT COUNT(1) FROM user
==> Parameters: 
<==      Total: 1
==>  Preparing: SELECT id,name,age,gender,email FROM user LIMIT ?,?
==> Parameters: 3(Long), 3(Long)
<==      Total: 3
User(id=4, name=David, age=26, gender=1, email=david@gmail.com)
User(id=5, name=Ellie , age=9, gender=0, email=ellie@gmail.com)
User(id=6, name=Frank, age=36, gender=1, email=frank@gmail.com)

测试IService接口中提供的page方法

其实Service层中的page方法与Mapper层的selectPage方法是类似的。

@Test
public void testPage(){
          
   
    Page<User> page1 = new Page<>(1, 3);
    // 查询年龄小于20的用户
    page1 = userService.page(page1,new QueryWrapper<User>().lt("age",20));
    page1.getRecords().forEach(System.out::println);
}

生成的sql语句及输出:

==>  Preparing: SELECT COUNT(1) FROM user WHERE (age < ?)
==> Parameters: 20(Integer)
<==      Total: 1
==>  Preparing: SELECT id,name,age,gender,email FROM user WHERE (age < ?) LIMIT ?
==> Parameters: 20(Integer), 3(Long)
<==      Total: 3
User(id=1, name=Alice, age=17, gender=0, email=alice@gmail.com)
User(id=2, name=Bob, age=19, gender=1, email=bob@gmail.com)
User(id=3, name=Colin, age=13, gender=1, email=colin@gmail.com)

- THE END -
经验分享 程序员 微信小程序 职场和发展