【问题标题】:How to retrieve all parents with children having many-to-one relationship defined in children entity in JPA?如何检索具有在 JPA 中的子实体中定义的多对一关系的孩子的所有父母?
【发布时间】:2021-06-05 18:17:05
【问题描述】:

实体A,

@Entity
class A {
    ...
    private String propertyA;
    private String propertyA1;
}

实体B

@Entity
class B {
    ...
    @ManyToOne()
    private A a;
    private String propertyB;
    private String propertyB1;
}

存储库

@Repository
interface A extends CrudRepository<A, Long> {
}
@Repository
interface B extends CrudRepository<B, Long> {
}

我怎样才能与他们的孩子一起检索所有 A(s)。我想要一个类似这样的 JSON 对象。

[
  {
    "propertyA": "..",
    "propertyA1": "..",
    "B": [
      {
        "propertyB": "1B",
        "propertyB1": "1B1"
      },
      {
        "propertyB": "2B",
        "propertyB1": "2B1"
      }
    ]
  },
  {
    "propertyA": "..",
    "propertyA1": "..",
    "B": [
      ...
    ]
  }
]

有没有办法在 JPA 中实现这一点?我是 Springboot 和 JPA 的新手。

【问题讨论】:

    标签: spring-boot jpa spring-data-jpa


    【解决方案1】:

    只需将@OneToMany(mappedBy = "a") @JsonProperty("B") private Set&lt;B&gt; bs; 添加到A。

    为此,您需要确保在持久性上下文仍处于打开状态时获取 bs 属性。您可以通过 (1) 将 fetch = EAGER 添加到 @OneToMany,(2) 使用带有查询的查询图来获取 A,或 (3) 通过将 spring.jpa.open-in-view 设置为 @ 来启用 OpenEntityManagerInViewFilter 987654329@.

    (取决于 SB 版本,spring.jpa.open-in-view 可能默认启用也可能不启用)

    【讨论】:

      猜你喜欢
      • 2018-02-12
      • 1970-01-01
      • 2015-04-18
      • 2016-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多