Mybatis-Plus 多表联查分页的实现代码

上一节,简单讲述了 Mybatis-Plus 搭建与使用入门,这一节,简单讲一下如何使用 MP 实现多表分页。

分析

使用的工程,依旧是 spring-boot,关于分页,官网给出了一个单表的demo,其实多表分页实现原理相同,都是通过 mybatis 的拦截器

(拦截器做了什么?他会在你的 sql 执行之前,为你做一些事情,例如分页,我们使用了 MP 不用关心 limit,拦截器为我们拼接。我们也不用关心总条数,拦截器获取到我们 sql 后,拼接 select count(*) 为我们查询总条数,添加到参数对象中)。

实现

1. 配置拦截器

@EnableTransactionManagement
@Configuration
@MapperScan("com.web.member.mapper")
public class MybatisPlusConfig {
  /**
   * mybatis-plus SQL执行效率插件【生产环境可以关闭】
   */
  @Bean
  public PerformanceInterceptor performanceInterceptor() {
    return new PerformanceInterceptor();
  }

  /*
   * 分页插件,自动识别数据库类型 多租户,请参考官网【插件扩展】
   */
  @Bean
  public PaginationInterceptor paginationInterceptor() {
    return new PaginationInterceptor();
  }
}

2. mapper 接口以及 xml

/**
 * 

* 用户表 Mapper 接口 *

* * @author 殷天文 * @since 2018-06-01 */ public interface UserMapper extends BaseMapper { List selectUserListPage(Pagination page ,@Param("user") UserListBean user); }

这里要注意的是,这个 Pagination page 是必须要有的,否则 MP 无法为你实现分页。

  

3. service 实现

import com.web.member.beans.admin.UserListBean;
import com.web.member.entity.User;
import com.web.member.mapper.UserMapper;
import com.web.member.model.UserListModel;
import com.web.member.service.UserService;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 

* 用户表 服务实现类 *

* * @author 殷天文 * @since 2018-06-01 */ @Service public class UserServiceImpl extends ServiceImpl implements UserService { @Transactional(readOnly=true) @Override public Page selectUserListPage(UserListBean user) { Page page = new Page<>(user.getCurr(), user.getNums());// 当前页,总条数 构造 page 对象 return page.setRecords(this.baseMapper.selectUserListPage(page, user)); } }

最后将结果集 set 到 page 对象中,page 对象的 json 结构如下

{
  "total": 48,//总记录
  "size": 10,//每页显示多少条
  "current": 1,//当前页
  "records": [//结果集 数组
    {...},
    {...},
    {...},
     ...
  ],
  "pages": 5 // 总页数
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(Mybatis-Plus 多表联查分页的实现代码)