用于查找具有空值的多个字段的 ExampleMatcher 配置

ExampleMatcher config for find multiple fields with null value

正在尝试使用 ExampleMatcher 查询查找多个字段。 在下面 class 我们有 4 个字段:

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

}

例如,现在我想搜索名称和电子邮件字段,而其他字段请求为空。结果应该是包含姓名和电子邮件请求的联系人列表。 我的搜索请求得到未知数量的字段。

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

此配置仅用于 phone 数字 return true 结果和其他字段 return null.

如果 Contact 实体有原始字段,那么它们的默认值实际上将用于创建查询。

如果不设置phoneNumber,会一直寻找phoneNumber = 0

您可以用 Wrapper 个字段替换 Primitive 个字段:

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

OR

您可以通过手动指定这些字段的名称来 ignore 原始字段:

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

.withIgnoreNullValues() 是您代码中 .withNullHandler(ExampleMatcher.NullHandler.IGNORE) 处理程序的 shorthand!