Spring Data ExampleMatchers by Example

13

我正在尝试理解如何使用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);

出于某种原因,我就是理解不了这个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
}

请问有人能给我展示如何构建一个ExampleMatcher的例子,以便我可以找到符合以下标准的Person记录:

  • 名字以"Sme"开头;并且
  • 姓氏长度不超过10个字符;并且
  • 出生日期早于1970年01月01日;并且
  • 分数在10到20之间(包括边界值)。

如果任何这些标准都无法使用ExampleMatcher实现,那没关系,但能否有人告诉我哪些标准可以或者解释一下哪些方法可以让我实现相似的功能?


3
请查看您指定的文件中的“限制”部分,其中提到:仅支持字符串的起始/包含/结束/正则表达式匹配和其他属性类型的精确匹配。 - pvpkiran
谢谢@pvpkiran (+1)。那么在这种情况下,您能否向我展示如何执行以下两个操作:**(1)** 过滤以“Sme”开头的名字,**(2)** 过滤得分恰好为50分的人?再次感谢! - smeeb
官方文档将会很有帮助:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example.matchers - Dusman
为了搜索在字符串s中输入的名字和在整数i中输入的分数的记录,如何编写匹配器?基本上,我想要为person类中的任何字段创建一个搜索示例。使用Example.of(person,ExampleMatcher.matching())。 - thealchemist
1个回答

24

你可以获取名字以"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)

1
使用此代码进行新版本 ExampleMatcher matcher = ExampleMatcher.matching() .withMatcher("firstName", new GenericPropertyMatcher().startsWith()) .withMatcher("score", new GenericPropertyMatcher().exact()); - ThinkTank
我是一个示例匹配器,用于过滤一些值,但如何使用它来过滤包含列表中列值的列。这意味着只要任何行包含列表中的列值,就可以使用@Query进行过滤,但与其他字段检查null一起使用会很难维护。 - Satish Patro
@ThinkTank,导入静态org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.startsWith; - Satish Patro
7
如何匹配一个集合,类似于$in? - Next Developer
1
嗨@NextDeveloper,你找到$in子句的解决方案了吗?如果找到了,能否请您发布解决方案? - Gaali Prabhakar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接