欢迎光临
我们一直在努力

Mybatis Plus怎么使用分页

这篇文章主要介绍了Mybatis Plus怎么使用分页的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Mybatis Plus怎么使用分页文章都会有所收获,下面我们一起来看看吧。

    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

    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);
        }

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

    3.注意

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

    4.如果你还有查询条件

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

    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);
    }

    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);
    }

    关于“Mybatis Plus怎么使用分页”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Mybatis Plus怎么使用分页”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注云搜网行业资讯频道。

    赞(0)
    【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。