SpringBoot 整合JPA | PageHelper 的分页最简实现

JPA又本身的Pageable来帮助咱们实现分页,Mybatis有PageHelper帮咱们实现分页,下面直接贴代码。git

1. 用JPA实现分页

1.1 pom添加依赖
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

复制代码

其实就是JPA的依赖。github

1.2 核心实现
/**
     * 查询所有
     */
    @Override
    public ServerResponse selectAll(Integer page,Integer size) {
        Pageable pageable = new PageRequest(page,size,Sort.Direction.DESC,"noticeId");
        Iterator<Notice> all = noticeRepostory.findAll(pageable).iterator();
        List<Notice> list = new ArrayList<Notice>();
        while (all.hasNext()){
           list.add(all.next());
        }
        if (all == null){
            return ServerResponse.createByErrorMessage("查询公告列表失败");
        }
        return ServerResponse.createBySuccess(list);
    }
复制代码

更多详细的请看spring boot2 整合(二)JPA(特别完整!)中分页那部分。spring

2. 用Mybatis实现分页

2.1 pom依赖
<dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.0.0</version>
        </dependency>

复制代码
2.2 核心代码
/**
     * 查询消息列表
     *
     * @param userId
     */
    @Override
    public ServerResponse selectNewsList(Integer userId,Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<News> news = newsMapper.selectNewsList(userId);
        PageInfo<News> appsPageInfo = new PageInfo<>(news);

        if (StringUtils.isEmpty(news)){
            return ServerResponse.createByErrorMessage("查询消息列表失败");
        }
        log.info("查询到的消息数目{}",appsPageInfo.getList());
        appsPageInfo.getList().forEach(p-> System.out.println(p.toString()));
        return ServerResponse.createBySuccess(appsPageInfo.getList());
    }
复制代码

咱们只须要PageHelper.startPage,而后紧跟着查询并返回一个list对象,而后用list对象建立一个PageInfo对象。bash

pageInfo有不少属性,好比当前页是多少,有没有下一页,数据一共多少等等,我这里调用它的getList方法来获取到news集合。app

更多详细的请看spring boot2 整合(一)Mybatis (特别完整!) 中分页那部分。ide

相关文章
相关标签/搜索