如何使ExampleMatcher只匹配一个属性?

Jig*_*igu 8 java matcher query-by-example spring-data

如何实现ExampleMatcher,从我的类中随机匹配一个属性并忽略其他属性?

假设我的课程是这样的:

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

如果我想按名称匹配:

Teacher TeacherExample = new Teacher("Peter");

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

如果我想按地址匹配:

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

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

pir*_*rho 8

尝试这个:

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

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

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

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

t.setArea(55);
Run Code Online (Sandbox Code Playgroud)

或者如果您有Date created,请通过创建进行搜索:

t.setCreated(someDate);
Run Code Online (Sandbox Code Playgroud)

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

来自文档

静态ExampleMatchermatching()
(&静态ExampleMatchermatchingAll())

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