【发布时间】:2020-07-29 22:01:59
【问题描述】:
鉴于以下域模型,我想加载所有 Answers,包括它们的 Values 和它们各自的子子级,并将其放入 AnswerDTO 中,然后转换为 JSON。我有一个可行的解决方案,但它遇到了我想通过使用临时@EntityGraph 来解决的 N+1 问题。所有关联都配置LAZY。
@Query("SELECT a FROM Answer a")
@EntityGraph(attributePaths = {"value"})
public List<Answer> findAll();
在Repository 方法上使用临时@EntityGraph,我可以确保预取值以防止Answer->Value 关联上的N+1。虽然我的结果很好,但还有另一个 N+1 问题,因为延迟加载了 MCValues 的 selected 关联。
使用这个
@EntityGraph(attributePaths = {"value.selected"})
失败,因为selected 字段当然只是Value 实体的一部分:
Unable to locate Attribute with the the given name [selected] on this ManagedType [x.model.Value];
如果值为MCValue,我如何告诉JPA 仅尝试获取selected 关联?我需要optionalAttributePaths之类的东西。
【问题讨论】:
标签: java postgresql hibernate jpa entitygraph