lester wrote:
I always think, that if you map your associations as lazy (in Hibernate 3.x it's the default mode), you don't have N+1 selects problem.
Well, actually it's exactly the contrary. If you map your relations eagerly, you won't encounter lazy-loading (quite straightforward). If you map it lazy="true", then accessing it will trigger a select for each element.
Imagine an association between students and teachers, let's say a Teacher has a list of students. If you retrieve all the teachers with something like
Code:
List<Teacher> teachers = session.createCriteria(Teacher.class).list();
Then, if you iterate on every teachers to display their students :
Code:
for(Teacher t : teachers)
{
for(Student s:t.getStudents())
{
// access some student property
}
}
Each getStudents() method call will trigger a select. That's what is called N+1 select syndroma.
If you don't want to meet this problem, just modify your code so as to force hibernate to change the lazy mode for the relation you want to be directly loaded, so your code would look like :
Code:
List<Teacher> teachers = session.setFetchMode("students",FetchMode.JOIN).createCriteria(Teacher.class).list();
This will do a select with a join to also retrieve the associated students with each teacher.
Hope this helps.