Mybatis-Plus使用分页

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Mybatis-Plus使用分页

草帽蓑衣下   2022-05-23 我要评论

Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生

1.写个Mybatis-plus配置类:

是通过拦截器实现分页

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

官网复制即可,只是你需要把数据库改为你使用的,这里我是使用mysql

image-20211127103508187

2.写接口测试

很简单

@GetMapping("/test")
    public Response test(){
        Page<Produce> producePage = new Page<>(1,1);
        Page<Produce> page = produceService.page(producePage);
        System.out.println(producePage == page);
        List<Produce> records = page.getRecords();
        for (Produce record : records) {
            System.out.println(record);
        }
        return new Response<>(records, ResultEnum.SUCCESS);
    }

image-20211127104035078

默认是会查询总条数,都有get、set方法,可以根据自己的需求设置(点开Page类看看)

image-20211127113428364

3.注意

我们传入的page对象和查询返回的page对象是同一个

image-20211127105657392

image-20211127105710551

4.如果你还有查询条件

比如我们只查询id和price,id小于5的分页查询

image-20211127112433085

1.Lambda表达式

@GetMapping("/test")
public Response test(){
    Page<Produce> producePage = new Page<>(1,2);
    Page<Produce> page = new LambdaQueryChainWrapper<>(produceService.getBaseMapper())
            .select(Produce::getPid,Produce::getPrice)
            .lt(Produce::getPid,5)
            .page(producePage);

    return new Response<>(page.getRecords(), ResultEnum.SUCCESS);
}

image-20211127112546762

2.普通查询

@GetMapping("/test")
public Response test(){
    Page<Produce> producePage = new Page<>(1,2);
    QueryWrapper<Produce> queryWrapper = new QueryWrapper<>();
    queryWrapper.select("pid","price");
    queryWrapper.lt("pid",5);
    Page<Produce> page = produceService.page(producePage, queryWrapper);
    return new Response<>(page.getRecords(), ResultEnum.SUCCESS);
}

image-20211127113153795

image-20211127113105586

总结 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们