How to do a find with pagination and search term at the same time with Spring data?

2

Hello, my question is the following. I want to do a search by passing a PageRequest and an Object or some search terms and get a list back. For example:

List getList (PageRequest page);

In this case I want the search to return the records referring to their respective Person fields (making a like with each of the fields).

Does anyone know how to do this using spring-data?

    
asked by anonymous 18.01.2018 / 04:44

1 answer

2

Since you want to use all the attributes of the object of type Pessoa , one of the ways is to use Query by Example (QBE) , then the first thing you should do to facilitate is to inherit from executor QueryByExampleExecutor in your repository . It will have methods that will create dynamic queries according to the attributes of the object.

We would have a repository similar to this:

public interface PessoaRepository extends CrudRepository<Pessoa, Long>, QueryByExampleExecutor<Pessoa> {}

An example usage would look something like this:

final Pessoa pessoa = ...;
final Example<Pessoa> example = Example.of(pessoa);
final Page<Pessoa> result = repository.findAll(example, pageRequest);

Other ways to use it is to change the return to a Slice or Stream and not a Page , as well as asynchronous forms , hence just in your repository write a query method like this:

Slice<Pessoa> findPessoaByExample(final Example<Pessoa> example, final Pageable page);

Now, using just a few attributes of the object, you would have a repository without also inheriting from QueryByExampleExecutor , like this:

public interface PessoaRepository extends PagingAndSortingRepository<Pessoa, Long> {}

An example query method would be this:

 Page<Pessoa> findByNomeIgnoreCaseAndIdade(final String nome, final Integer idade, final Pageable page);

Assuming that in type Pessoa there are such attributes:

@Entity
public Pessoa {

    private String nome;

    private Integer idade;

}

Notice that in this case the query would increase whenever you needed a new attribute in the query. You can also use some other extension like Query DSL , which also helps query dynamics through their predicates.

Regardless of the form of use, ensure that your Pageable object is the last parameter of the method repository , this is the default used by Spring for queries instantiation. In addition, for the examples I've considered JPA, if it's another kind of persistence please let me know, but using the common spring data works on other persistence types.

    
18.01.2018 / 13:01