Mybatis-plus最简实现分页查询

前言

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

一、添加依赖的Jar包

1
2
3
4
5
6
7
8
9
10
11
xml复制代码<!--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

1
2
3
4
5
6
7
8
9
10
11
12
java复制代码@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中添加分页查询函数

1
2
3
4
5
6
7
8
9
10
java复制代码@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构造函数如下:

1
2
3
java复制代码public Page(long current, long size) {
this(current, size, 0);
}

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
arduino复制代码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;
}

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%