javaspringjpaspring-dataquery-by-example

ExampleMatcher config for find multiple fields with null value


Trying to find multiple fields with ExampleMatcher query. in below class we have 4 field:

public class contact {
  private String name;
  private long phoneNumber; //primary
  private String email;
  private String organization;

}

Now for example I want to search with name and email fields and other fields request are null. result should be list of contacts that contain name and email request. My search request get unknown number of fields.

ExampleMatcher userExampleMatcher = ExampleMatcher.matchingAll()
            .withNullHandler(ExampleMatcher.NullHandler.IGNORE);
    Iterable<Contact> contacts = dao.findAll(Example.of(contactObject, userExampleMatcher));

This config just for phone number return true result and for other fields return null.


Solution

  • If the Contact entity has primitive fields, then their default value will actually be used for creating the query.

    If not setting the phoneNumber, it will always look for phoneNumber = 0

    You can replace Primitive fields with Wrapper fields:

    public class Contact {
        private String name;
        private Long phoneNumber;
        private String email;
        private String organization;
    }
    

    OR

    You can ignore primitive fields by manually specifying names of these fields:

    ExampleMatcher userExampleMatcher = ExampleMatcher.matchingAll()
                    .withIgnorePaths("phoneNumber").withIgnoreNullValues();
    

    The .withIgnoreNullValues() is the shorthand for the .withNullHandler(ExampleMatcher.NullHandler.IGNORE) handler in your code!