gabriel119435
gabriel119435

Reputation: 6802

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?

Upvotes: 18

Views: 44762

Answers (2)

pvpkiran
pvpkiran

Reputation: 27018

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.

Upvotes: 22

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

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

Upvotes: 15

Related Questions