See an example using Query
and PageRequest
, with a dummy entity called Pessoa
in which I use JPQL:
public interface PessoaCrudRepository extends CrudRepository<Pessoa, Long> {
@Query(value = "SELECT p FROM Pessoa p WHERE p.nome = ?1")
Page<Pessoa> buscarPessoa(String nomePessoa, Pageable pageable);
}
And to call and use:
int numeroPagina = 0;
int numeroResultados = 10;
PageRequest pageRequest = new PageRequest(numeroPagina, numeroResultados,
Sort.Direction.ASC, "nome");
Page<Pessoa> pagePessoa = repository.buscarPessoa("Jonas", pageRequest);
List<Pessoa> pessoas = pagePessoa.getContent();
If you want to use notation by method name to create queries (without writing JPQL), you can just write:
public interface PessoaCrudRepository extends CrudRepository<Pessoa, Long> {
Page<Pessoa> findByNome(String nomePessoa, Pageable pageable);
}
If none of the solutions above meet, depending on the complexity of your query, you have to break into something more flexible by using the Query
class and giving up Spring pagination and manipulating the String
of the query according to the filters. You can even continue using PageRequest
as a class to pass paging data (so you do not escape the pattern of your code), but its application in your method must be explicit in Query
. Example:
String jpql = "SELECT p FROM Pessoa p WHERE p.nome = :nome";
Query query = entityManager.createQuery(jpql);
query.setParameter("nome", "Jonas");
query.setFirstResult(pageRequest.getPageNumber() * pageRequest.getPageSize());
query.setMaxResults(pageRequest.getPageSize());
List<Pessoa> pessoas = query.getResultList();