上一节,简单讲述了 Mybatis-Plus 搭建与使用入门,这一节,简单讲一下如何使用 MP 实现多表分页。
分析
使用的工程,依旧是 spring-boot,关于分页,官网给出了一个单表的demo,其实多表分页实现原理相同,都是通过 mybatis 的拦截器
(拦截器做了什么?他会在你的 sql 执行之前,为你做一些事情,例如分页,我们使用了 MP 不用关心 limit,拦截器为我们拼接。我们也不用关心总条数,拦截器获取到我们 sql 后,拼接 select count(*) 为我们查询总条数,添加到参数对象中)。
实现
1. 配置拦截器
@EnableTransactionManagement
@Configuration
@MapperScan("com.web.member.mapper")
public class MybatisPlusConfig {
@Bean
public PerformanceInterceptor performanceInterceptor() {
return new PerformanceInterceptor();
}
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
2. mapper 接口以及 xml
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; @Service public class UserServiceImpl extends ServiceImplimplements 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 // 总页数
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



