Databases Reference
In-Depth Information
The source code of the relevant methods is given as follows:
private Pageable buildPageSpecification(int pageIndex, int pageSize) {
Sort sortSpec = sortByLastNameAndFirstNameAsc();
return new PageRequest(pageIndex, pageSize, sortSpec);
}
private Sort sortByLastNameAndFirstNameAsc() {
return new Sort(new Sort.Order(Sort.Direction.ASC, "lastName"),
new Sort.Order(Sort.Direction.ASC, "firstName")
);
}
Implementing pagination
In order to paginate the results of our queries, we have to pass the created
PageRequest
object to a correct repository method. This method depends on the
approach, which we are using to build our queries. Each of these approaches is
described in this subsection.
JpaRepository
Because the
ContactRepository
extends the
JpaRepository<T,ID>
interface, we
got access to the
Page<Contact> findAll(Pageable page)
method that we can
use to paginate the list of all entities. The implementation of the
findAllForPage()
method of the
RepositoryContactService
class is described as follows:
1.
We get the used
PageRequest
object.
2.
We get a reference to
Page<Contact>
by calling the repository method and
passing the
PageRequest
object as parameter.
3.
We return a list of contacts.
The source code of our
findAllForPage()
method is given as follows:
@Transactional(readOnly = true)
@Override
public List<Contact> findAllForPage(int pageIndex, int pageSize) {
Pageable pageSpecification = buildPageSpecification(pageIndex,
pageSize);
Page<Contact> page = repository.findAll(pageSpecification);
return page.getContent();
}