Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Custom Query with pageable

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.

like image 747
Trivikrama Avatar asked Dec 04 '14 14:12

Trivikrama


People also ask

How do I create a custom query in spring boot?

We can use @Query annotation to specify a query within a repository. Following is an example. In this example, we are using JPQL, Java Persistence Query Language. We've added name query custom methods in Repository in JPA Named Query chapter.

How can you configure JPQL query for a query method in a repository in Spring data JPA?

In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm.xml file.

How does Spring Pageable work?

Spring Data REST Pagination In Spring Data, if we need to return a few results from the complete data set, we can use any Pageable repository method, as it will always return a Page. The results will be returned based on the page number, page size, and sorting direction.


1 Answers

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.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.

like image 97
d0x Avatar answered Sep 21 '22 02:09

d0x