Databases Reference
In-Depth Information
Adding pagination support to a query method
We can add pagination support to a query method that is annotated with the
@Query
annotation by making the following changes to its signature:
1.
We add the
Pageable
interface as a parameter of the method.
2.
We determine the return type of the method.
At this point we are not interested in the metadata of the returned page. Thus, the
declaration of the query method is given as follows:
@Query("SELECT c FROM Contact c WHERE LOWER(c.firstName) LIKE
LOWER(:searchTerm) OR LOWER(c.lastName) LIKE LOWER(:searchTerm)")
public List<Contact> findContacts(@Param("searchTerm") String
searchTerm, Pageable page);
Modifying the service method
The implementation of the
search()
method of the
RepositoryContactService
class is described as follows:
1.
We get the used like pattern.
2.
We get a reference to the used
PageRequest
object.
3.
We get the list of contacts by calling the query method and passing the like
pattern and the created
PageRequest
object as a parameter.
The source code of the
search()
method is given as follows:
@Transactional(readOnly = true)
@Override
public List<Contact> search(SearchDTO dto) {
String likePattern = buildLikePattern(dto.getSearchTerm());
Pageable pageSpecification = buildPageSpecification(dto.
getPageIndex(), dto.getPageSize());
return repository.findContacts(likePattern, pageSpecification);
}