Mybatis-plus最简实现分页查询

5,926 阅读1分钟

前言

四步实现myBatis-plus的分页查询: 添加依赖包->添加Interceptor->定义三件套->使用page函数;

一、添加依赖的Jar包

<!--MP插件-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.3.1</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.3.1</version>
</dependency>

二、添加Interceptor

@Configuration
public class MybatisPlusPageInterceptor {
    /**
     * mybatis-plus分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        return page;
    }

}

三、添加DO,Mapper,Service三件套

我们以TStation,TStationMapper,TStationServiceImpl为例

image.png

四、在service中添加分页查询函数

@Service
public class TStationServiceImpl extends ServiceImpl<TStationMapper, TStation> implements ITStationService {
    @Override
    public IPage<TStation> listPage(Map queryParam,Integer page,Integer size) {
        LambdaQueryWrapper<TStation> queryWrapper = Wrappers.lambdaQuery();
        //根据queryParam设置Wrapper的查询条件
        //比如:queryWrapper.eq(TStation::getFrameNo,queryParam.get("frameName"));
        return page(new Page<>(page,size), queryWrapper);
    }
}

总结:

1.分页查询时,需要通过Page对象设置查询条件“current”和“size”,Page构造函数如下:

public Page(long current, long size) {
    this(current, size, 0);
}

2.分页查的结果为IPage,用来存储查询结果,可以通过getRecord()来获取具体结果集;

IPage<TStation> containerPage = itStationService.listPage(null,1,20);//取第1页,每页20条
containerPage.getRecords().forEach(record -> {
    //可以对结果集中的数据干点啥
});

3.IPage的查询条件,不仅限于current,size;还有其他查询条件可以设置,如:total,isSearchCount;

public Page(long current, long size) {
    this(current, size, 0);
}

public Page(long current, long size, long total) {
    this(current, size, total, true);
}

public Page(long current, long size, boolean isSearchCount) {
    this(current, size, 0, isSearchCount);
}

public Page(long current, long size, long total, boolean isSearchCount) {
    if (current > 1) {
        this.current = current;
    }
    this.size = size;
    this.total = total;
    this.isSearchCount = isSearchCount;
}