NamedEntityGraph仍然导致延迟加载异常

时间:2018-08-09 16:34:58

标签: sql hibernate jpa spring-data-jpa entitygraph

我具有以下实体结构:

Route: -one-to-many-> :Stop: <-many-to-many-> :Child: <-many-to-many-> :Contact

因此,我在每个实体类的顶部定义了以下命名实体图,以便可以优化查询此层次结构需要走多远的查询:

路线:

@NamedEntityGraphs({
        @NamedEntityGraph(name = "Route.stop.child.contact",
                attributeNodes = {
                        @NamedAttributeNode(value = "stops", subgraph = "Stop.child.contact")
                }),
        @NamedEntityGraph(name = "Route.stop.child",
                attributeNodes = {
                        @NamedAttributeNode(value = "stops", subgraph = "Stop.child")
                }),
        @NamedEntityGraph(name = "Route.stop",
                attributeNodes = {
                        @NamedAttributeNode(value = "stops", subgraph = "Stop")
                })
})
public class Route {...}

停止:

@NamedEntityGraphs({
        @NamedEntityGraph(name = "Stop.child.contact",
                attributeNodes = {
                        @NamedAttributeNode(value = "children", subgraph = "Child.contact")
                }),
        @NamedEntityGraph(name = "Stop.child",
                attributeNodes = {
                        @NamedAttributeNode(value = "children", subgraph = "Child")
                }),
        @NamedEntityGraph(name = "Stop", attributeNodes = {})
})
public class Stop {...}

孩子:

@NamedEntityGraphs({
        @NamedEntityGraph(name = "Child.contact",
                attributeNodes = {
                        @NamedAttributeNode(value = "contacts", subgraph = "Contact")
                }),
        @NamedEntityGraph(name = "Child", attributeNodes = {})
})
public class Child {...}

联系方式:

@NamedEntityGraphs({@NamedEntityGraph(name = "Contact", attributeNodes = {})})
public class Contact {...}

我在自己的Repository类中使用它们,例如:

@EntityGraph(value = "Route.stop.child.contact", type = EntityGraph.EntityGraphType.LOAD)
Optional<Route> findRouteStopsChildrenContactsByRouteId(short routeId);

但是,我看不到任何联接查询,当我尝试访问Stop的子级时会抛出lazyinit异常。我的理解是,这就是实体图可用于优化查询的方式(即,当我必须为每个单独的站点获取子对象时,n + 1问题),但是我没有运气让它起作用。

关于我在做什么错的任何建议?

1 个答案:

答案 0 :(得分:0)

尝试这个对我有用的东西。

@NamedEntityGraph(name = "Book.details", attributeNodes = @NamedAttributeNode("reviews"))
@Table(name = "Book")
public class Book  implements Serializable
{
    @OneToMany(cascade = CascadeType.ALL , mappedBy = "book" , fetch = FetchType.EAGER)
    //@OrderBy("no ASC")
    private List<Review> reviews ; 
}

2)获取记录(内部使用左外部联接)。

@EntityGraph(value = "Book.details", type = EntityGraphType.FETCH)
  List<Book> getBooksByAuthName(String aname);