其他分享
首页 > 其他分享> > Spring Data ExampleMatchers by Example

Spring Data ExampleMatchers by Example

作者:互联网

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

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无法实现这些标准中的任何一个,那很好,但有人可以告诉我哪些是或者解释哪些方法可能让我接近我正在寻找的东西?

解决方法:

您可以获取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)

标签:spring,spring-data,spring-data-jpa,query-by-example
来源: https://codeday.me/bug/20190527/1162606.html