Databases Reference
In-Depth Information
JPA Criteria API
In order to build queries with the JPA Criteria API, the
ContactRepository
interface
must extend the
JpaSpecificationExecutor<T>
interface. This gives us access to
the
Page<Contact> findAll(Specification spec, Pageable page)
method that
can be used to paginate the query results of criteria queries. The only thing that is left
for us to do is to modify the
search()
method of the
RepositoryContactService
class. Our implementation is explained as follows:
1. We get the used specification.
2.
We get the used
PageRequest
object.
3.
We get the
Page
implementation by calling the repository method and
passing the specification and the
PageRequest
object as a parameter.
4.
We return the requested list of contacts by calling the
getContent()
method
of the
Page
class.
The source code of our search method is given as follows:
@Transactional(readOnly = true)
@Override
public List<Contact> search(SearchDTO dto) {
Specification<Contact> contactSpec =
firstOrLastNameStartsWith(dto.getSearchTerm());
Pageable pageSpecification = buildPageSpecification(dto.
getPageIndex(), dto.getPageSize());
Page<Contact> page = repository.findAll(contactSpec,
pageSpecification);
return page.getContent();
}
Querydsl
Since the
ContactRepository
interface extends the
QueryDslPredicateExecutor<T>
interface, we got access to the
Page<Contact>
findAll(Predicate predicate, Pageable page)
method that we can use
to paginate query results. In order to add pagination support to our search
function, we have to make some changes to the existing
search()
method of the
RepositoryContactService
class. The new implementation of this method is
described in the following steps:
1.
We get a reference to the used
Predicate
.
2.
We get the used
PageRequest
object.