• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

MyBatis Plus 实现多表分页查询功能的示例代码

mybatis 搞代码 4年前 (2022-01-09) 21次浏览 已收录 0个评论

在Mybatis Plus 中,虽然IService 接口帮我们定义了很多常用的方法,但这些都是 T 对象有用,如果涉及到 多表的查询,还是需要自定义Vo 对象和自己编写sql 语句,Mybatis Plus提供了一个Page 对象,查询是需要设置其中的 size 字段 和 current 字段的值

一、分页配置

可以直接使用selectPage这样的分页,但返回的数据确实是分页后的数据,但在控制台打印的SQL语句其实并没有真正的物理分页,而是通过缓存来获得全部数据中再进行的分页,这样对于大数据量操作时是不可取的,那么接下来就叙述一下,真正实现物理分页的方法。
官方在分页插件上如是描述:自定义查询语句分页(自己写sql/mapper),也就是针对自己在Mapper中写的方法,但经过测试,如果不配置分页插件,其默认采用的分页为RowBounds的分页即逻辑分页,也就是先把数据记录全部查询出来,然在再根据offset和limit截断记录返回(数据量大的时候会造成内存溢出),故而不可取,而通过分页插件的配置即可达到物理分页效果。

新建一个MybatisPlusConfig配置类文件,代码如下所示:

import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
public class MybatisPlusConfig {
 
  /**
   * mybatis-plus分页插件<br>
   */
  @Bean
  public PaginationInterceptor paginationInterceptor() {
    PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
    return paginationInterceptor;
  }
}

二、使用分页进行单表的查询

对于单表的分页查询,ServiceImpl 类已经为我们提供了对应的方法 selectPage(),并将结果封装到Page 对象中:

在项目开发当中,都会将分页的一些参数封装成一个类 PageReq(不要在意这个Req 为什么不是全大写)->import java.io.Serializable;

public class PageReq implements Serializable {

  /**
   * 每页显示大小
   */
  private long size;

  /**
   * 当前页码
   */
  private long current;

  /**
   * 最大页数
   */
  private long maxCurrent;

  /**
   * 数据总条数
   */
  private long total;

  public long getSize() {
    return size;
  }

  public void setSize(long size) {
    this.size = size;
  }

  public long getCurrent() {
    return current;
  }

  public void setCurrent(long current) {
    this.current = current;
  }

  public long getMaxCurrent() {
    return maxCurrent;
  }

  public void setMaxCurrent(long maxCurrent) {
    this.maxCurrent = maxCurrent;
  }

  public long g<mark style="color:transparent">本文来源gaodaimacom搞#^代%!码网@</mark>etTotal() {
    return total;
  }

  public void setTotal(long total) {
    if(size != 0){
      if(total % size != 0){
        maxCurrent = total / size + 1;
      }else {
        maxCurrent = total / size;
      }
    }
  }

  public PageReq() {

  }

  public PageReq(long size, long current, long total) {
    this.size = size;
    this.current = current;
    this.total = total;
    setTotal(total);
  }
}

功能编写:


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:MyBatis Plus 实现多表分页查询功能的示例代码
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址