It’s a very simple mapping.
The database is mysql5.0
User <-one to many-> Blog
mappings:
<class name="com.aaa.model.User" table="users">
<id name="id" column="ID">
<generator class="native"></generator>
</id>
<property name="username" column="USERNAME" type="string"/>
<property name="age" column="AGE" type="int"/>
<set name="blogs" inverse="true" fetch="join">
<key column="userid"/>
<one-to-many class="com.aaa.model.Blog"/>
</set>
</class>
<class name="com.aaa.model.Blog" table="blog">
<id name="id" column="ID">
<generator class="native"></generator>
</id>
<property name="name" column="NAME" type="string" length="50"/>
<property name="hits" column="HITS" type="integer" length="11"/>
</class>
I use the “fetch=join” in the <set> property,When I use the session.get() method to get the User instance like that
User user = (User)session.get(User.class, new Long(1));
for (Blog blog : user.getBlogs()) {
System.out.println(blog.getName());
}
the output SQL is still “N+1”
select
user0_.ID as ID0_0_,
user0_.USERNAME as USERNAME0_0_,
user0_.AGE as AGE0_0_
from
users user0_
where
user0_.ID=?
select
blogs0_.userid as userid0_1_,
blogs0_.ID as ID1_,
blogs0_.ID as ID1_0_,
blogs0_.NAME as NAME1_0_,
blogs0_.HITS as HITS1_0_
from
blog blogs0_
where
blogs0_.userid=?
I try it in hibernate 3.2 and 3.6 ,the result is same ,is this a bug or something?
I think the fetch strategy will only be applied if the association is eagerly fetched. You didn’t mark the set with
lazy="false", so the set is lazy-loaded the first time it’s accessed.Note that setting
lazy="false"will make Hibernate load the blogs of a user each time the user is loaded. You should perhaps let the association withlazy="true", and use an ad-hoc HQL query with join fetching when you need a user with his blogs: