Spring Custom request with page

I want to implement pagination in a spring application.I know using a repository we can implement pagination, but we cannot write our own query to retrieve data, there are limited methods in the repository, so there is no method that accepts a request class .

If we want to write our custom query to retrieve data from mongodb, we must use mongotemaplete, since I know that with mongotemplate we cannot implement pagination.

Is there any other way to implement pagination along with db queries. anyone can help me.

+3
source share
4 answers

As you found out, MongoTemplate does not support full page abstraction. Like KneeLess, you can use @Query-Annotation to do some custom queries.

In case this is not enough, you can use the Spring Repository PageableExecutionUtilsin combination with your MongoTemplate.

For example, for example:

@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 do the same. As you can see here , they also run two queries.

+9
source

Extending the Spring Data PagingAndSortingRepository interface , you can get some common methods, such as save, find, findAll and delete, and 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);

}
+1

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 like

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

Just put it in case someone needs it.

SpringData has a method for user request:

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

Source: https://habr.com/ru/post/1684625/


All Articles