Mybatis-plus的条件构造器(查看官方文档)
https://baomidou.com/guide/wrapper.html
1:实现简单的条件查询
在上次使用Mybatis-plus的基础上,在controller层中的基本查询添加基本的条件查询
比如我要查询指定名字的学生(比如表中的 “一个普通的学生”)
将此前的查询全部学生的方法稍作修改为如下
@GetMapping("getallstudent")
public Result getStudent(){
// QueryWrapper 构造一些查询条件
QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
studentQueryWrapper.eq("name","一个普通的学生");
return Result.ok(iStudentService.list(studentQueryWrapper));
}
可以看到找到的结果就是我们所需要的了。
再加一个条件,查找名字是“一个普通的学生”的同时,年龄大于19的数据
studentQueryWrapper.eq("name","一个普通的学生")
.gt("age",19);
让两个条件是or的关系
studentQueryWrapper.eq("name","一个普通的学生").or()
.gt("age",19);
在之间加一个.or()就行
还有更多的查询条件可以参考官方文档,这里就不一一列举了。
https://baomidou.com/guide/wrapper.html
2:分页查询
首先添加一个分页工具类
package com.mybatis.mybatis.utils;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor page = new PaginationInterceptor();
return page;
}
}
分页查询方法
// currentPage 需要查询第几页
// pageSize 每页查询的数量
@GetMapping("getStudentPage/{pageSize}/{currentPage}")
public Result getStudentPage(@PathVariable int pageSize,@PathVariable int currentPage){
Page<Student> page = new Page<>(currentPage,pageSize);
IPage<Student> studentIPage = iStudentService.page(page,null);
return Result.ok(studentIPage);
}