Spring Data ExampleMatchers by Example

sme*_*eeb 7 spring query-by-example spring-data spring-data-jpa

我试图了解如何使用Spring Data的Query by Example功能,并且正在努力了解如何使用ExampleMatcher它及其各种with*方法.使用匹配器的经典示例包括以下代码段:

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

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

Example<Person> example = Example.of(person, matcher);
Run Code Online (Sandbox Code Playgroud)

出于某种原因,我无法将我的大脑包裹在这个DSL上.我们Person来自文档中的示例.假设一个Person实体看起来像这样:

// 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
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以向我展示如何构建一个ExampleMatcher允许我找到Person符合以下条件的记录的示例:

  • 名字以" Sme " 开头; 和
  • 姓氏长度不超过10个字符; 和
  • 出生日期是1970-01-01之前; 和
  • 得分在10到20之间,包括在内

如果这些标准中的任何一个都不可能ExampleMatcher,那很好,但有人可以告诉我哪些是或者解释什么方法可能让我接近我正在寻找的东西?

pvp*_*ran 13

您可以获取firstName以"Sme"开头且得分= 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)
Run Code Online (Sandbox Code Playgroud)

  • 知道如何匹配一个集合吗? (7认同)