Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the total number of pages on Spring Data?

I have an Angular app that shows a list of entities and I have a 'show more' button that increments page number and uses this method:

Page<myEntity> result = myRepo.findByAttr(attr, page);

I format this result and send it via REST's JSON. I want to disable 'show more' button if there's no further pages to get. There's a 'frameworkie' specific way to retrieve this number or I should use findAll() and count through this list?

like image 867
rado Avatar asked May 30 '18 15:05

rado


People also ask

What is page in Spring data JPA?

1. Overview. Pagination is often helpful when we have a large dataset and we want to present it to the user in smaller chunks. Also, we often need to sort that data by some criteria while paging. In this tutorial, we'll learn how to easily paginate and sort using Spring Data JPA.

What is page <> in Java?

A page is a sublist of a list of objects. It allows gain information about the position of it in the containing entire list.

What is spring pagination?

Pagination is used to display a large number of records in different parts. In such case, we display 10, 20 or 50 records in one page. For remaining records, we provide links. We can simply create pagination example in Spring MVC. In this pagination example, we are using MySQL database to fetch records.

What is JPA pagination?

Pagination is a simple but important feature to limit the size of your result set to a number of records that can get efficiently processed by your application and the user. You can configure it with JPA and Hibernate by calling the setFirstResult and setMaxResults on the Query or TypedQuery interface.


2 Answers

This is the source code of Page interface

public interface Page<T> extends Slice<T> {

    /**
     * Returns the number of total pages.
     * 
     * @return the number of total pages
     */
    int getTotalPages();

    /**
     * Returns the total amount of elements.
     * 
     * @return the total amount of elements
     */
    long getTotalElements();

    /**
     * Returns a new {@link Page} with the content of the current one mapped by the given {@link Converter}.
     * 
     * @param converter must not be {@literal null}.
     * @return a new {@link Page} with the content of the current one mapped by the given {@link Converter}.
     * @since 1.10
     */
    <S> Page<S> map(Converter<? super T, ? extends S> converter);
}

You have getTotalElements() to get the total number of matching element.
getTotalPages() will give total number of pages.

like image 120
pvpkiran Avatar answered Oct 03 '22 02:10

pvpkiran


Use result.getTotalElements() to get the total number of matching element.

Use result.getTotalPages() to get the total number of page.

p.s. Use result.getContent() to get the content as List<>

like image 36
Mạnh Quyết Nguyễn Avatar answered Oct 03 '22 01:10

Mạnh Quyết Nguyễn