Tom Lensburry
Tom Lensburry

Reputation: 74

How do I lazy load a nested collection?

I have an entity Parent and a relation @OneToMany to another entity Child. The collection children is set to lazy loading.

@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();
    }
}

I get the famous

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

exception in the test() method on the line where I access the children list.

I don't want to change the fetch type annotation in the entity.

How do I access the child entities?

Upvotes: 0

Views: 1389

Answers (1)

Tom Lensburry
Tom Lensburry

Reputation: 74

I found the culprit. The transaction management was disabled.

The @Transactional annotation was missing from the test method.

To enable transaction management, put this in application-context.xml:

<tx:annotation-driven />

There is nothing wrong with the code, but the configuration was incomplete. To eagerly load nested collections all we need is an embracing transaction.

Turning on debug logging for org.springframework.orm and org.hibernate helped me to identify the source of the issue.

Similar question and answer: LazyInitializationException in JPA and Hibernate

Upvotes: 1

Related Questions