【问题标题】:Howto make ExampleMatcher with containing just one property?如何使 ExampleMatcher 只包含一个属性?
【发布时间】:2019-02-27 17:36:29
【问题描述】:

如何实现 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(..) 如何避免这种情况?

【问题讨论】:

    标签: java spring-data matcher query-by-example


    【解决方案1】:

    试试这个:

    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 -&gt; Integer 这样的盒装类型,没有其他简单的解决方法。

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

    t.setArea(55);
    

    或者如果您有 Date created,则按 created 搜索:

    t.setCreated(someDate);
    

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

    来自the docs

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

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

    【讨论】:

    • 我认为这对我不起作用,因为我还有其他数字类型的属性。 (整数区域)。当我创建新老师时,该区域将默认为 java 填充 0。(不能为空),因为它是整数。
    • 而且,如果我也有日期时间类型的属性呢??
    • @JiguJigu 更新了答案。使用新的详细信息更新您的问题,而不是将它们作为有助于其他人回答的评论。
    • 我将属性类型更改为整数。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 2012-07-09
    • 2017-09-02
    • 1970-01-01
    相关资源
    最近更新 更多