Spring Data ExampleMatchers by Example

smeeb picture smeeb · Feb 2, 2018 · Viewed 16.4k times · Source

I'm trying to understand how to use Spring Data's Query by Example capabilities, and am struggling to understand how to use ExampleMatcher and its various with* methods. Classic examples of the matcher in use includes snippets like this:

Person person = new Person();                          
person.setFirstname("Dave");                           

ExampleMatcher matcher = ExampleMatcher.matching()     
  .withIgnorePaths("lastname")                         
  .withIncludeNullValues()                             
  .withStringMatcherEnding();                          

Example<Person> example = Example.of(person, matcher);

For some reason, I just can't wrap my brain around this DSL. Let's take the Person example from the docs. Let's say a Person entity looks like this:

// Pseudo code; omitting JPA annotations for this example
public class Person {
    private String firstName;
    private String lastName;
    private Date dob;
    private Long score;

    // Getters, setters & constructor omitted
}

Can anyone show me an example of how to construct an ExampleMatcher that would allow me to find Person records meeting the following criteria:

  • First name starts with "Sme"; and
  • Last name is less than 10 characters long; and
  • Date of birth is before 1970-01-01; and
  • Score is between 10 and 20, inclusively

If any of these criteria aren't possible with ExampleMatcher, that's fine, but can someone show me which ones are or explain what methods might get me close to what I'm looking for?

Answer

pvpkiran picture pvpkiran · Feb 2, 2018

You can get records with firstName starting with "Sme" and score=50

Person person = new Person();
person.setFirstName("Sme");
person.setScore(50L);
ExampleMatcher matcher = ExampleMatcher.matching()
    .withMatcher("firstName", startsWith())
    .withMatcher("score", exact());

Example<History> example = Example.of(person, matcher);
personRepository.findAll(example)