Loading

SpringBoot+MongoDB实现分页查询(倒序)

后端

 @Override
    public Page<StrategyComment> queryPage(StrategyCommentQuery qo) {
        // totalPage  prePage nextPage
        Query query = new Query();
        Criteria criteria = new Criteria();
        if (qo.getStrategyId() != null) {
            criteria = Criteria.where("strategyId").in(qo.getStrategyId());
            query.addCriteria(criteria);
        }
        // 模糊匹配
        if (qo.getKeyword() != null) {
            String keyword = qo.getKeyword();
            String pattern = ".*" + keyword + ".*"; // 正则表达式
            criteria.orOperator(Criteria.where("strategyTitle").regex(pattern),Criteria.where("content").regex(pattern));// 多条件模糊查询
            query.addCriteria(criteria);
        }
        // totalCount
        long totalCount = mongoTemplate.count(query, StrategyComment.class);
        // 如果没数据,可以优化性能不用继续执行了
        if (totalCount == 0) {
            return Page.empty();
        }
        // data
        // 第一个参数 从 0 开始
        Sort orderBy = Sort.by(Sort.Direction.DESC, "createTime"); //倒序
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),orderBy);
        query.with(pageable);
        List<StrategyComment> data = mongoTemplate.find(query, StrategyComment.class);
        // 三个参数 List<T> content, Pageable pageable, long total
        return new PageImpl<StrategyComment>(data, pageable, totalCount);
    }

前端

<div th:fragment="mongoPage" style="text-align: center;">
    <ul id="pagination" class="pagination"></ul>
    <script>
        //分页
        $(function () {
            var totalPages = [[${page.totalPages}]]
            var startPage = [[${page.pageable.pageNumber}+1]]

            $("#pagination").twbsPagination({
                totalPages: totalPages || 1,
                startPage: startPage || 1,
                visiblePages: 5,
                first: "首页",
                prev: "上页",
                next: "下页",
                last: "尾页",
                initiateStartPageClick: false,
                onPageClick: function (event, page) {
                    $("#currentPage").val(page);
                    $("#searchForm").submit();
                }
            });
        })
    </script>
</div>

如果不想分页,想实现倒序,可以参考下面代码

 @GetMapping("/comments")
    public Object comments(Long travelId){
        List<TravelComment> commentList = travelCommentRepository.findByTravelId(travelId,Sort.by(Sort.Direction.DESC, "createTime"));
       return JsonResult.success(commentList);
    }
@Repository
public interface TravelCommentRepository extends MongoRepository<TravelComment,String> {
    /**
     * 按时间倒序查询出所有评论
     */
    List<TravelComment> findByTravelId(Long travelId, Sort createTime);
}
posted @ 2021-08-17 16:13  JereCode  阅读(2315)  评论(0编辑  收藏  举报