HIbernate and eager loading of collections
I have a 1-many relationship between class A
and class B
, represented by a foreign key relation between two tables in the database. and I want hibernate to eagerly load the collection of B
s so that it can be traversed outside a session.
So I specify lazy="false"
on both the one-to-many and many-to-one mapping entry.
B.hbm
:
<many-to-one cascade="all" fetch="join" lazy="false"
class="A" name="...">
<column name="adgroup_id"/>
</many-to-one>
A.hbm
<list cascade="all" inverse="true" name="..." lazy="false" fetch="join">
<key column="adgroup_id" />
<one-to-many class="B" />
</list>
I notice that the sql executed by hibernate indeed returns the expected number of rows, but when I call
A.getBs()
, I get too many elements. Indeed, since my ids in the database are auto-assigned, it seems to return n+1 elements where n is the cu开发者_JAVA技巧rrently highest id in the table of B
s.
What is going on here ?
I am using the Spring hibernate template btw, calling template.get(class,id)
to return the A
Very good description of n+1 problem: What is SELECT N+1?
精彩评论