Reputation: 29527
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:
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?
Upvotes: 14
Views: 30481
Reputation: 27048
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)
Upvotes: 26