See an example using Query
and PageRequest
, with a fictional entity called Pessoa
where 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 to 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 method name notation to create queries (without writing JPQL), you can write only:
public interface PessoaCrudRepository extends CrudRepository<Pessoa, Long> {
Page<Pessoa> findByNome(String nomePessoa, Pageable pageable);
}
If none of the above solutions meet, depending on the complexity of your query, you have to go for something more flexible using the class Query
and giving up Spring paging and manipulating the String
of the query according to the filters. You can even continue using the PageRequest
as a class to pass paging data (not to deviate from the default of your code), but its application in your method should 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();