How to make a find with Pagination and search term at the same time with Spring data?

Asked

Viewed 807 times

2

Hey, here’s my question. 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,Person person person);

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

Can anyone tell me how to do it using spring-date ?

1 answer

2


How you want to use all attributes of the type object Pessoa, one of the ways is to use Query by Example (QBE), then the first thing you must do to facilitate is to inherit also from the executioner QueryByExampleExecutor in his Repository. In it you will have methods that will create dynamic queries according to the attributes of the object.

We would have a Repository like this:

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

An example of use would be something like this:

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

Other forms of use is to change the return to a Slice or Stream and not a Page, beyond forms asynchronous, hence enough in your Repository write a query method like this:

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

Now, using only a few attributes of the object, you would have a repository without inheriting too from QueryByExampleExecutor, thus:

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

An example of a 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;

}

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

Regardless of the form of use always ensure that your object Pageable is the last parameter of method Repository, this is the pattern used by Spring for instropection of darlings. Also, for the examples I considered JPA, if it is another kind of warning persistence, it may have, but using the common spring data works on other types of persistence.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.