Can subgraph reference another named entity graph?
Asked Answered
B

1

9

So I have found a few answers where one says it is possible to do so and the other says it is not. This kind of confused me because when I tried to do so - I failed.

What I want is to reference a named entity graph in a subgraph like that:

@Entity
@Table(name = "parent")
@NamedEntityGraphs({
    @NamedEntityGraph(
        name = "Parent.all",
        attributeNodes = {
            @NamedAttributeNode(value = "child", subgraph = "Child.all"), // here I am referencing graph specified in Child entity
        }
    )
})
public class ParentModel {

  @OneToOne(
      mappedBy = "parent",
      fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
  private ChildModel child;

}
@Entity
@Table(name = "child")
@NamedEntityGraphs({
    @NamedEntityGraph(
        name = "Child.all",
        attributeNodes = {
            @NamedAttributeNode(value = "grandChildren"),
        }
    )
})
public class ChildModel {

  @OneToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "parent_id")
  private ParentModel parent;

  @OneToMany(
      mappedBy = "child",
      fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
  private Set<GrandChild> grandChildren;

}

And I want to use the Spring Data repository method:

@EntityGraph(value = "Parent.all")
List<ParentAll> findAll();

But I am still getting LazyInitializationException when I want to reference the grandChildren like parent.child.grandChildren (note, as soon as I manually add @NamedSubgraph to Parent entity - everything works fine). So is it possible to do so in order to make the code cleaner and not repeat yourself? Am I missing something here?

Baldhead answered 26/2, 2021 at 5:18 Comment(0)
P
0

As far as I know, you have to define named graphs and subgraphs separately, because the subgraph has to be of type NamedSubgraph, not NamedEntityGraph.

@NamedEntityGraph(
    name = "Parent.all", attributeNodes = {
        @NamedAttributeNode(value = "child", subgraph = "Child.all")},
    subgraphs = {
        @NamedSubgraph(name = "Child.all", attributeNodes = @NamedAttributeNode("grandChildren"))}
)
Putrescent answered 21/4, 2022 at 19:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.