Spring Data Jpa分页

/ Spring Boot / 没有评论 / 57浏览

介绍Spring Data Jpa中最优雅的分页

Controller

@GetMapping
public ResultVO<Page<Mood>> page(@RequestParam(required = false) String title,
                                 @PageableDefault Pageable pageable) {
    return ResultVO.ok(moodService.page(title, pageable));
}

注意:page从0开始

Service

没啥业务逻辑,直接调用Dao

public Page<Mood> page(String title, Pageable pageable) {
    return moodDao.page(title, pageable);
}

Dao

public Page<Mood> page(String title, Pageable pageable) {
    return page(Criteria.where("title").regex(title), pageable);
}

public Page<T> page(Criteria criteria, Pageable pageable) {
    Query query = Query.query(criteria);
    Long count = count(query);
    if (count == 0L) {
        return new PageImpl<>(Collections.emptyList(), pageable, count);
    }
    List<T> list = find(query.with(pageable));
    return new PageImpl<>(list, pageable, count);
}