首页 > 解决方案 > 如何使 ExampleMatcher 只包含一个属性?

问题描述

如何实现 ExampleMatcher,从我的类中随机只包含一个属性而忽略其他属性?

假设我的班级是这样的:

Public Class Teacher() {
    String id;
    String name;
    String address;
    String phone;
    int area;
    ..other properties is here...
}

如果我想按名称匹配:

Teacher TeacherExample = new Teacher("Peter");

ExampleMatcher matcher = ExampleMatcher.matchingAny()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
.withIgnoreCase()
.withIgnorePaths("id", "address", "phone","area",...);   //no name 

如果我想按地址匹配:

ExampleMatcher matcher = ExampleMatcher.matchingAny()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
.withIgnoreCase()
.withIgnorePaths("id", "name", "phone","area",...); //no address

所以我需要重复withIgnorePaths(..)如何避免这种情况?

标签: javaspring-datamatcherquery-by-example

解决方案


试试这个:

Teacher t = new Teacher("Peter");
Example<Teacher> te = Example.of(t,
    ExampleMatcher.matching()
        .withStringMatcher(StringMatcher.CONTAINING)
        .withIgnoreCase());

与示例教师中的所有非空字段进行比较ExampleMatcher.matching()或比较,因此只需命名(假设来自“Peter”)。ExampleMatcher.matchingAll()t

注意:对于原始值,您只需将它们添加到withIgnorePaths(..)或更改为盒装类型,例如int -> Integer,没有其他简单的解决方法。

如果您只需要通过int area不设置名称进行搜索,但在您的示例中t

t.setArea(55);

或者如果你有Date created,搜索创建:

t.setCreated(someDate);

您甚至可以将它们全部设置为通过应用它们来缩小搜索范围。

文档

静态 ExampleMatcher 匹配()
( & 静态 ExampleMatcher matchingAll() )

创建一个包含所有非空属性的新 ExampleMatcher,默认匹配从示例派生的所有谓词。


推荐阅读