【问题标题】:Spring Data ExampleMatchers by ExampleSpring Data ExampleMatchers 示例
【发布时间】:2018-07-12 12:27:18
【问题描述】:

我正在尝试了解如何使用 Spring Data 的 Query by Example 功能,并且正在努力了解如何使用 ExampleMatcher 及其各种 with* 方法。使用中的 matcher 的经典示例包括如下 sn-ps:

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 无法满足这些条件中的任何一个,那很好,但有人可以告诉我哪些是或解释哪些方法可以让我接近我在找吗?

【问题讨论】:

  • 检查您指定的文档中的限制部分,它说仅支持字符串的开始/包含/结束/正则表达式匹配和其他属性类型的精确匹配
  • 谢谢@pvpkiran (+1) 所以在这种情况下,你能告诉我如何做以下两件事:(1) 过滤以 " 开头的名字Sme" 和 (2) 过滤正好为 50 的分数?再次感谢!
  • @pvpkiran 为了搜索在字符串中给出名字作为输入的记录,比如 s 和在整数中作为输入给出的分数,我该如何编写匹配器?基本上,对于人员类中任何字段的任何字符串,我想如何创建搜索示例。使用 Example.of(person, ExampleMatcher.matching())

标签: spring spring-data spring-data-jpa query-by-example


【解决方案1】:

您可以获取 firstName 以“Sme”开头且 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)

【讨论】:

  • 将此代码用于新版本 ExampleMatcher matcher = ExampleMatcher.matching() .withMatcher("firstName", new GenericPropertyMatcher().startsWith()) .withMatcher("score", new GenericPropertyMatcher()。精确());
  • 我是过滤某些值的示例匹配器,但是如何使用它来过滤带有列表的列。意味着只要任何行包含列表中的列值。我可以使用 @Query 但与其他字段一起使用检查 null 将很难维护
  • @ThinkTank,导入静态 org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.startsWith;
  • 知道如何匹配一个集合,比如 $in 吗?
  • 嗨 @NextDeveloper 你找到 $in 子句的解决方案了吗?如果你这样做了,你能发布解决方案吗
猜你喜欢
  • 2018-02-06
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2015-02-21
  • 2021-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多