前言
此前学习了条件构造器查询,一定要记住几个常用的查询方法(比如id,queryWrapper的使用,和连接词估计不常用的也快忘光了),这个比较像Hibernate的QBC,还算可以。这篇介绍MP中的分页查询
这个是自己学习时候记得笔记要是想详细了解可以去MP官网,上边有更详细的配置流程以及视频教学:MyBatis-Plus
分页前言
还记得MyBatis中,需要引入pageHelper来执行分页查询,它的本质是先在数据库中查询符合条件的所有到记录,pageHelper会自动根据分页设置的条件那去所需记录,实际上没有用到 limit 语句。而MP提供了分页插件可以解决此问题
配置
在根目录下+package config,此包下创建类MyBatisPlusConfig(包名类名自定义即可)
主要是@Configuration将此类声明为配置,将分页插件声明为Bean
@Configuration
public class MyBatisPlusConfig {
// 分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}
使用
- 需要返回值为List< Entity >对象时
- new Page<>(当前页数,每页几条)
- new Page<>(当前页数,每页几条,是否查询总记录数)
- 对于不需要知道总条数的查询,可指定第三个参数为false;否则不指定时默认true,还会在查询一个总条数
- IPage< Entity> 为查询结果;Page< Entity>为分页设置
public List<Type> selectTypePage() {
QueryWrapper<Type> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("type_id", 2);
Page<Type> typePage = new Page<>(1, 2);
IPage<Type> typeIPage = this.typeMapper.selectPage(typePage, queryWrapper);
System.out.println("总页数" + typeIPage.getPages());
System.out.println("总记录数" + typeIPage.getTotal());
System.out.println("总页数" + typeIPage.getPages());
return typeIPage.getRecords();
}
- 需要返回值为List< Map >对象
- 跟返回Entity不同点就是泛型上的不同
public List<Map<String, Object>> selectMapPage() {
QueryWrapper<Type> queryWrapper = new QueryWrapper<>();
queryWrapper.lt("type_id", 2);
Page<Map<String, Object>> typePage = new Page<>(1, 2);
IPage<Map<String, Object>> typeIPage = this.typeMapper.selectMapsPage(typePage, queryWrapper);
System.out.println("总页数" + typeIPage.getPages());
System.out.println("总记录数" + typeIPage.getTotal());
System.out.println("总页数" + typeIPage.getPages());
return typeIPage.getRecords();
}