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?
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.
A page is a sublist of a list of objects. It allows gain information about the position of it in the containing entire list.
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.
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.
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.
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<>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With