views:

23

answers:

1

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.

+1  A: 

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
Albert