Aayush Puri
Aayush Puri

Reputation: 1899

Batch load a lazily loaded Hibernate property

Suppose I have a:

class Student {
    int id;
    String name;
    List<Course> courses; //Lazily loaded as per Hiberante config
}

Now suppose I have a List students and in order to optimize fetching List for all these students, I was to batch select them rather than letting Hibernate call a separate SQL one by one. I cannot turn off lazy loading as in many other code paths I will not access course property.

I can certainly write a function that will take in a list of courseIds and return a List and then attach these objects to the Hibernate session but these objects won't be associated with the Student objects loaded by Hibernate. If I call something like student.setCourses(), then I run into the risk that Hibernate will consider the session to be dirty and try updating the Student objects.

I would really like to hear from people who have faced similar issues when using Hibernate.

Upvotes: 1

Views: 431

Answers (1)

Albert
Albert

Reputation: 2115

Write a specific hibernate query to get the student class with a 'join fetch' to get all related courses in a single query. Example:

from Student s left join fetch s.courses

Upvotes: 1

Related Questions