自由的羽毛 发表于 2023-6-10 13:39:16

分页查询和条件分页查询

分页查询

分析:

[*]分析文档要求
[*]查看前端传递给后台的参数
[*]分析参数进行编码
[*]后台返回给前端的数据
思路
浏览器 - > Controller层 - > Service层 - > Mapper层 - > 数据库


设置分页拦截器
@Configuration
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
      // 创建MybatisPlusInterceptor拦截器对象
      MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
      // 添加分页拦截器
      mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
      return mpInterceptor;
    }
}IPage分页对象的常用调用方法
​        IPage内部原理是基于拦截去,拦截的是方法以及方法中的参数,会判断是否查询操作。如果是查询操作,才会进入分页的逻辑处理。进入分页的逻辑处理后,拦截器会通过反射获取该方法的参数进行判断是否存在IPage对象的实体类。如果不存在就不进行分页,存在则将该参数赋值给IPage对象。再进行拼接sql处理完成IPage对象。
void selectPage() {
    // 1 为当前页码2 为每页的记录数
        IPage<User> page=new Page<>(1,3);
        userDao.selectPage(page,null);
        System.out.println("当前页码值:"+page.getCurrent());
        System.out.println("每页显示数:"+page.getSize());
        System.out.println("一共多少页:"+page.getPages());
        System.out.println("一共多少条数据:"+page.getTotal());
        System.out.println("数据:"+page.getRecords());
}流程

Controller层
@RestController
@RequestMapping("/emps")
public class EmpController {
   
    @Autowired
    private EmpService empService;

// @RequestParam使用defaultValue属性设置默认值
// @GetMapping请求映射的地址
@GetMapping
    public Result selectLimit(@RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer pageSize) {
      // 调用业务层进行查询
      PageBean pageBean = empService.selectLimit(page, pageSize);
      // 返回打包封装后的数据
      return Result.success(pageBean);
    }
}Service层


@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {

    @Autowired
    private EmpMapper empMapper;

    @Override
    public PageBean selectLimit(Integer page, Integer pageSize) {
      // 定义Emp实体对象封装操作类
      QueryWrapper<Emp> queryWrapper = new QueryWrapper<>();
      // 进行分页查询
      IPage<Emp> iPage = new Page<>(page, pageSize);
      iPage = empMapper.selectPage(iPage, queryWrapper);

      //封装返回值 返回
      return new PageBean(iPage.getTotal(), iPage.getRecords());
    }
}Mapper层

@Mapper
public interface EmpMapper extends BaseMapper<Emp> {

}条件分页查询

Controller 层


[*]接受参数(分页参数, 查询条件)
[*]调用service进行条件分页查询, 获取pagebean
[*]响应
Service 层

借阅:MyBatis-Plus分页插件IPage的使用展示------分页查询_mybatisplus ipage_星域_03zhan的博客-CSDN博客

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: 分页查询和条件分页查询