如何实现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(..)
如何避免这种情况?
试试这个:
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匹配() (&static ExampleMatcher matchingAll())
创建一个新的ExampleMatcher,包括默认情况下匹配从示例派生的所有谓词的所有非null属性。