8

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?

Brad Parks
  • 66,836
  • 64
  • 257
  • 336
Jigu Jigu
  • 145
  • 1
  • 10

1 Answers1

8

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.

pirho
  • 11,565
  • 12
  • 43
  • 70
  • I think this is not working for me, since i have other properties with numeric type. (int area). When i create new teacher, that area will be fill with 0 by java default.(can't be null) since it's integer. – Jigu Jigu Feb 28 '19 at 04:22
  • And, how if I also have properties with datetime type ?? – Jigu Jigu Feb 28 '19 at 04:26
  • @JiguJigu updated the answer. Update also your question with new details instead of putting them as a comment it helps others to answer. – pirho Feb 28 '19 at 06:20
  • i change the property type to Interger. Thank You – Jigu Jigu Feb 28 '19 at 18:45