【问题标题】:JPA findBy multiple items optionallyJPA findBy 多个项目可选
【发布时间】:2019-06-03 17:33:10
【问题描述】:

我正在为一个丑陋的问题寻找一个简单的解决方案。我正在使用 Spring Data JPA 并且有 7 个相关的实体。我需要做一个 findByEntity1_NameAndEntity2_NameAndEntity3_NameAndEntity4_NameAndEntity5_NameAndEntity6_NameAndEntity7_Name

我需要每个排列,包括和排除这些实体。我可以构建所有 128 种方法并使用一个大的 case 语句来选择要使用的方法,但这非常难看。我觉得我错过了这个简单的按钮。

【问题讨论】:

  • 使用原生查询会更容易实现吗?

标签: spring-data-jpa spring-data


【解决方案1】:

示例查询方法

我认为对您来说最好的选择是使用 Spring Data JPA 的(imo,有点不常用)QueryByExample 功能。在研究这个答案时,I posted an answer somewhere else 需要相同的响应。我会看一下,以了解这如何解决您的问题。

您首先需要将QueryByExampleExecutor 转至您的Repository。 其次,您只需要像这样创建您的查询(希望您为您的实体使用fluent builders!):

ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues();
Example<MyObject> exampleQuery = Example.of(new MyObject()
    .withEntity1(new Entity1().withName("foo"), matcher);
repository.findAll(exampleQuery);

将选择所有MyObject 元素,其中Entity1 具有namefoo

ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues();
Example<MyObject> exampleQuery = Example.of(new MyObject()
    .withEntity1(new Entity1().withName("foo"),
    .withEntity2(new Entity2().withName("bar"),
    .withEntity3(new Entity3().withName("baz"),
    .withEntity4(new Entity4().withName("foo"),
    .withEntity5(new Entity5().withName("bar"),
    .withEntity6(new Entity6().withName("baz"),
    .withEntity7(new Entity7().withName("foo")
), matcher);
repository.findAll(exampleQuery);

将为Entity1namefooEntity2namebar 等选择所有MyObject 元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2011-09-11
    相关资源
    最近更新 更多