Spring Custom Query with pageable

≡放荡痞女 提交于 2020-01-10 14:13:07

问题


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 limited methods in repository that too there is no method accepting query class.

If we want to write our custom query to retrieve data from mongodb we have to use mongotemaplete, as i know with mongotemplate we can not implement pagination.

Is there any another way to implement pagination along with db queries. any one can help me.


回答1:


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<XXX> findSophisticatedXXX(/* params, ... */ @NotNull Pageable pageable) {

    Query query = query(
            where("...")
            // ... sophisticated query ...
    ).with(pageable);

    List<XXX> list = mongoOperations.find(query, XXX.class);
    return PageableExecutionUtils.getPage(list, pageable,
              () -> mongoOperations.count(query, XXX.class));
}

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




回答2:


Use MongoRepository. Extend MongoRepository as

public interface FooRepository extends MongoRepository<Foo,String> {    
    @Query(value="{'name': ?0}");
    Page<Foo> findByMethod(String name, Pageable pageable);
}

Then, use it as

Page fooPage = FooRepository.findByMethod('John', new PageRequest(0,20));



回答3:


Just putting it out in case someone needs it.

SpringData has a method for custom query:

final Pageable pageableRequest = new PageRequest(0, 2);
Query query = new Query();
query.with(pageableRequest);



回答4:


By extending Spring Data PagingAndSortingRepository interface you can get some common methods such as save, find, findAll and delete and also you can add your own custom queries:

public interface Repository extends PagingAndSortingRepository<Book, ID extends Serializable> {

    // Common method
    Page<Book> findAll(Pageable pageable);

    // Custom query based on Spring Data naming convention
    Page<Book> findByNameOrDescription(String name, String description, Pageable pageable);

}


来源:https://stackoverflow.com/questions/27296533/spring-custom-query-with-pageable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!