注意:本教程使用的数据库脚本、数据模型和环境信息请参考 “MyBatis Plus环境准备” 章节,点击下载示例源码。
在 IService 接口中提供了很多以 page 开头的方法,这些方法均会接收一个 IPage 参数,该参数封装了分页信息。MyBatis Plus 提供了 IPage 接口的默认实现 Page,代码如下:
/**
* 简单分页模型
*
* @author hubin
* @since 2018-06-09
*/
public class Page<T> implements IPage<T> {
private static final long serialVersionUID = 8545996863226528798L;
/** 查询数据列表 */
protected List<T> records = Collections.emptyList();
/** 总数 */
protected long total = 0;
/** 每页显示条数,默认 10 */
protected long size = 10;
/** 当前页 */
protected long current = 1;
/** 排序字段信息 */
protected List<OrderItem> orders = new ArrayList<>();
/** 自动优化 COUNT SQL */
protected boolean optimizeCountSql = true;
/** 是否进行 count 查询 */
protected boolean isSearchCount = true;
/** 是否命中count缓存 */
protected boolean hitCount = false;
protected String countId;
protected Long maxLimit;
}IServer 接口 page 方法定义如下:
// 无条件分页查询 IPage<T> page(IPage<T> page); // 条件分页查询 IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper); // 无条件分页查询 IPage<Map<String, Object>> pageMaps(IPage<T> page); // 条件分页查询 IPage<Map<String, Object>> pageMaps(IPage<T> page, Wrapper<T> queryWrapper);
参数说明:
page:翻页对象
queryWrapper:实体对象封装操作类 QueryWrapper
(1)下面示例将对数据进行分页,每一页大小为5,取出第二页的数据。即 new Page(2, 5),其中:2表示第二页,5表示页面大小。代码如下:
package com.hxstrive.mybatis_plus.simple_service.page;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hxstrive.mybatis_plus.model.UserBean;
import com.hxstrive.mybatis_plus.service.UserService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
class Page1Test {
@Autowired
private UserService userService;
@Test
void contextLoads() {
Page<UserBean> page = new Page(2, 5);
userService.page(page);
for(UserBean userBean : page.getRecords()) {
System.out.println(userBean);
}
}
}(2)使用 QueryWrapper 筛选所有薪水大于7000,性别为男的用户,然后对其进行分页。代码如下:
package com.hxstrive.mybatis_plus.simple_service.page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hxstrive.mybatis_plus.model.UserBean;
import com.hxstrive.mybatis_plus.service.UserService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
class Page2Test {
@Autowired
private UserService userService;
@Test
void contextLoads() {
QueryWrapper<UserBean> wrapper = new QueryWrapper<>();
wrapper.gt("salary", 7000);
wrapper.eq("sex", "男");
Page<UserBean> page = new Page(2, 5);
userService.page(page, wrapper);
for(UserBean userBean : page.getRecords()) {
System.out.println(userBean);
}
}
}
非常棒的教程,感谢
谢谢支持!