如何延迟加载嵌套集合?

How do I lazy load a nested collection?

我有一个实体 Parent 和一个与另一个实体 Child 的关系 @OneToMany。子集合设置为延迟加载。

@Entity
class Parent{
    @Id
    String parentId;
    @OneToMany(mappedBy="parent",fetch=FetchType.LAZY)
    List<Child> children;
}

@Entity
class Child{
    @Id
    String childId;
    @ManyToOne
    @JoinColumn(name="parentId")
    Parent parent;
}

List<Parent> loadParents() {
    QParent qParent = QParent.parent;
    List<Parent> parentList = query.select(qParent).from(qParent).fetch();
    return parentList;
}

@Transactional
void test(){
    List<Parent> parentList = loadParents();
    for(Child child:parentList.getChildren()){
        child.getChildId();
    }
}

我出名了

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role ... could not initialize proxy - no Session

在我访问子列表的那一行的 test() 方法中出现异常。

我不想更改实体中的提取类型注释。

如何访问子实体?

我找到了罪魁祸首。事务管理被禁用。

测试方法中缺少 @Transactional 注释。

启用事务管理,请将其放入应用程序-context.xml:

<tx:annotation-driven />

代码没有问题,但配置不完整。要急切地加载嵌套集合,我们只需要一个拥抱事务。

为 org.springframework.orm 和 org.hibernate 打开调试日志帮助我确定了问题的根源。

类似问答:LazyInitializationException in JPA and Hibernate