1.首先先写上配置类:
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@MapperScan("com.demo.carsell.carsell.dao")//配置自动扫描的包
@Configuration
public class MyBatisConfig {
//引入分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
PaginationInterceptor paginationInterceptor=new PaginationInterceptor();
//设置请求界面大于最大页的操作,true返回首页,false继续请求,默认false
paginationInterceptor.setOverflow(true);
//设置单页最大记录数
paginationInterceptor.setLimit(1000);
return paginationInterceptor;
}
}
2.写一个工具类来存放分页信息:
package com.demo.carsell.carsell.until;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.List;
/**
* 分页工具类
*
*/
public class PageUtils implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 总记录数
*/
private int totalCount;
/**
* 每页记录数
*/
private int pageSize;
/**
* 总页数
*/
private int totalPage;
/**
* 当前页数
*/
private int currPage;
/**
* 列表数据
*/
private List<?> list;
/**
* 分页
* @param list 列表数据
* @param totalCount 总记录数
* @param pageSize 每页记录数
* @param currPage 当前页数
*/
public PageUtils(List<?> list, int totalCount, int pageSize, int currPage) {
this.list = list;
this.totalCount = totalCount;
this.pageSize = pageSize;
this.currPage = currPage;
this.totalPage = (int)Math.ceil((double)totalCount/pageSize);
}
/**
* 分页
*/
public PageUtils(IPage<?> page) {
this.list = page.getRecords();
this.totalCount = (int)page.getTotal();
this.pageSize = (int)page.getSize();
this.currPage = (int)page.getCurrent();
this.totalPage = (int)page.getPages();
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getCurrPage() {
return currPage;
}
public void setCurrPage(int currPage) {
this.currPage = currPage;
}
public List<?> getList() {
return list;
}
public void setList(List<?> list) {
this.list = list;
}
}
3.进行分页查询:
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<XXXEntity> page = this.page(
new Query<XXXEntity>().getPage(params),
new QueryWrapper<XXXEntity>()
);
List<XXXEntity> list=XXXDao.selectList(new QueryWrapper<XXXEntity>());
PageUtils pageUtils=new PageUtils(page);
pageUtils.setTotalCount(list.size());
pageUtils.setTotalPage((int)(list.size())/10+1);
return pageUtils;
}
params参数如下:
page=2, limit=10, key=