javaspring-datamatcherquery-by-example

How to make ExampleMatcher to match just one property?


How to implement ExampleMatcher, to match just one property randomly from my class and ignore the other properties?

Assume my class like this :

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

If I want to match by the name:

Teacher TeacherExample = new Teacher("Peter");

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

and if I want to match by the address:

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

so I need to repeat the withIgnorePaths(..) How to avoid that?


Solution

  • Try this:

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

    With ExampleMatcher.matching() or ExampleMatcher.matchingAll() comparison is done against all non-null fields in your example teacher t so just name (assumed from "Peter").

    NOTE: with primitive values you just need to add them to withIgnorePaths(..) or change them to boxed types like int -> Integer, there are no other easy workarounds.

    If you need to search only by int area set no name but are in your example t

    t.setArea(55);
    

    or if you had Date created, searching by created:

    t.setCreated(someDate);
    

    you can even set them all to narrow the search by applying them all.

    From 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.