如何使 ExampleMatcher 只包含一个 属性?

Howto make ExampleMatcher with containing just one property?

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

假设我的 class 是这样的:

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(..) 如何避免?

试试这个:

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

使用 ExampleMatcher.matching()ExampleMatcher.matchingAll() 比较是针对示例教师 t 中的所有非空字段进行的,所以只需名称(从 "Peter" 假设)。

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

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

t.setArea(55);

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

t.setCreated(someDate);

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

来自the docs

static ExampleMatcher matching()
( & static ExampleMatcher matchingAll() )

Create a new ExampleMatcher including all non-null properties by default matching all predicates derived from the example.