【问题标题】:Spring JPA Query By Example Match One Null Field but Ignore OthersSpring JPA查询示例匹配一个空字段但忽略其他
【发布时间】:2020-04-13 05:24:20
【问题描述】:

使用 JPA 通过示例查询时,有没有办法为一列而不是全部指定空匹配?似乎 Null 匹配只能应用于所有列。

class Entity {
  private Integer id;
  private String name;
  private Instant createdAt;
  private Instant deletedAt;
  // getters and setters
}

通过示例查询时,我想在示例中包含deletedAt 实际上为空的情况,但忽略其他字段上的空匹配。在数据库中,created_at 列是TIMESTAMP WITHOUT TIME ZONE 列(postgresql)

编辑:Spring data query where column is null 中提出的解决方案不适用,因为它们没有利用示例查询

【问题讨论】:

  • 这能回答你的问题吗? Spring data query where column is null
  • 如果可以的话,另一个解决方案是使用本机查询。
  • @medTech 本机查询不会给我通过示例查询的好处。而且您的第一个链接可以使用,但似乎也不适用于示例。我可能不得不使用规范

标签: java spring hibernate jpa spring-data-jpa


【解决方案1】:

您可以尝试使用ExampleMatcher 实现您想要的。特别是ExampleMatcher.includeNullValues() 和/或ExampleMatcher.withIgnorePaths("deletedAt")

尝试一种或两种:

ExampleMatcher exampleMatcher = ExampleMatcher.matchingAll()
                                               .withIgnorePaths("deletedAt")
                                               .withIncludeNullValues();
Example<Entity> ex = Example.of(obj, exampleMatcher);

【讨论】:

  • 使用此设置,我需要手动忽略所有为空的值。我希望空匹配能够正常工作(忽略空值),除非我想在 deletedAt 为空时完全匹配
猜你喜欢
  • 2020-05-31
  • 2011-06-05
  • 2020-07-30
  • 2017-10-08
  • 2020-05-28
  • 2020-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多