JUnior Vieira
JUnior Vieira

Reputation: 3

Spring data order search correctly

In my Repository i create the folowing method:

List<customer> findTop5ByNameContains(String name);

imagining that I have these customers:

[{name: 'spongebob', id: 1}, {name: 'Bob dylan', id: 2}]

, when i search 'bob', the result comes: spongebob, Bob Dylan. How to sort first the records that start with the parameter and then the records that contain the parameter?

Upvotes: 0

Views: 139

Answers (2)

Rodrigo Dantas
Rodrigo Dantas

Reputation: 36

I should recommend you to use and "Exemple Matcher"

i.e.:

public List<Customer> search(Customer customer) {
  ExampleMatcher matcher = ExampleMatcher
            .matching()
            .withIgnoreCase()
            .withIgnoreNullValues()
            .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
            .withMatcher("name", startsWith())
            .withIgnorePaths("id");
  Example<Customer> query = Example.of(customer, matcher);

  return repository.findAll(query);
}

Upvotes: 0

Cristiano Bombazar
Cristiano Bombazar

Reputation: 1042

According with the docs, you should use "Starting with". Try this:

 List<customer> findTop5ByNameStartingWith(String name);

Upvotes: 1

Related Questions