Spring Custom Query with pageable

前端 未结 6 756
自闭症患者
自闭症患者 2020-12-30 07:29

I want to to implement pagination in spring application.I know using repository we can implement pagination but we can not write our own query for data retrieve there are li

6条回答
  •  死守一世寂寞
    2020-12-30 08:02

    As you figured out, MongoTemplate doesn't support the complete page abstraction. Like KneeLess said you can use the @Query-Annotation to do some custom queries.

    In case this isn't enough for you, can use utilize the Spring Repository PageableExecutionUtils in combination with your MongoTemplate.

    For example like this:

    @Override
    public Page findSophisticatedXXX(/* params, ... */ @NotNull Pageable pageable) {
    
        Query query = query(
                where("...")
                // ... sophisticated query ...
        ).with(pageable);
    
        List list = mongoOperations.find(query, XXX.class);
        return PageableExecutionUtils.getPage(list, pageable,
                  () -> mongoOperations.count((Query.of(query).limit(-1).skip(-1), XXX.class));
    }
    

    Spring Repositories are doing the same. As you can see here, they fire two queries as well.

提交回复
热议问题