MyBatis-Plus分页查询的简单实现案例

首先准备项目,参考MyBatis-Plus快速开始再进行分页案例

1. Application中导入分页插件

@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    return interceptor;
}

2. 创建UserService接口并实现IService

public interface UserService extends IService<User> {

}

3.实现UserService

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

4. 自定义的mapper方法使用分页

  方法
//传入参数携带Ipage接口
//返回结果为IPage
public interface UserMapper extends BaseMapper<User> {

    //定义一个根据年龄参数查询,并且分页的方法 age > xx
    IPage<User> queryByAge(IPage<User> page, @Param("age") Integer age);

}
  接口实现
<select id="selectPageVo" resultType="xxx.xxx.xxx.User">
    SELECT * FROM user WHERE id > #{id}
</select>

4. 测试

Page

该类继承了 IPage 类,实现了简单分页模型,如果要实现自己的分页模型可以继承 Page 类或者实现 IPage 类

属性名类型默认值描述
recordsListemptyList查询数据列表
totalLong0查询列表总记录数
sizeLong10每页显示条数,默认 10
currentLong1当前页
ordersListemptyList排序字段信息,允许前端传入的时候,注意 SQL 注入问题,可以使用 SqlInjectionUtils.check(…) 检查文本
optimizeCountSqlbooleantrue自动优化 COUNT SQL 如果遇到 jSqlParser 无法解析情况,设置该参数为 false
optimizeJoinOfCountSqlbooleantrue自动优化 COUNT SQL 是否把 join 查询部分移除
searchCountbooleantrue是否进行 count 查询,如果只想查询到列表不要查询总记录数,设置该参数为 false
maxLimitLong单页分页条数限制
countIdStringxml 自定义 count 查询的 statementId 也可以不用指定在分页 statementId 后面加上 _mpCount 例如分页 selectPageById 指定 count 的查询 statementId 设置为 selectPageById_mpCount 即可默认找到该 SQL 执行
@Test
public void testQuick(){

    IPage page = new Page(1,2);

    userMapper.selectPageVo(page,2);

    long current = page.getCurrent();//页码
    System.out.println("current = " + current);
    long pages = page.getPages();
    System.out.println("pages = " + pages);
    long total = page.getTotal();
    System.out.println("total = " + total);
    List records = page.getRecords();
    System.out.println("records = " + records);

}
@Test
    public void testMyPage(){
        Page<User> page = new Page<>(1,3);
        userMapper.queryByAge(page,1);

        long current = page.getCurrent(); //页码
        System.out.println("current = " + current);
        long size = page.getSize(); //页容量
        System.out.println("size = " + size);
        List<User> records = page.getRecords(); //当前页的数据
        System.out.println("records = " + records);
        long total = page.getTotal(); //总条数
        System.out.println("total = " + total);

    }
  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值