那天去了达内,试听了2个小时的课,刚好讲的他们的当当网项目,讲hibernate表关系映射这段来了,不过也够呛,投影仪看的眼睛点都不舒服,当时讲的也没认真听,听了个大概,就记住那个老师一句话了,说是有经验的人用的,一般人不告诉,就是说这个join fetch 用法,回来查了一下,用起来比较爽,今晚突然来了兴致,小记一下。
join fetch 其实是相当于 数据库 里面的连接部分。默认是inner join 。也支持left outer join。
join fetch 主要是运用于 HQL 中。
主要体现在一对多、多对多的关系表中
例如:
class Student{
private int id;
private int name;
private Team team;
get{…} ; set{…};
}
class Team{
private int tid;
private String name;
private Set
students; get{…}; set{…}';
}
默认查询Team 的时候,fetch=lazy,不会去查询 Team 中所有的Student.
----------------查询---------------------
Team t=(Team)session.load(Team.class, 3);
Set
for(Student s:sets){
System.out.println(s.getId()+" "+s.getName());
}
----------------查询结果-----------------
Hibernate:
select
team0_.cid as cid0_0_,
team0_.name as name0_0_
from
team0_
where
team0_.cid=?
Hibernate:
select
students0_.cid as cid0_1_,
students0_.id as id1_,
students0_.id as id1_0_,
students0_.cid as cid1_0_,
students0_.name as name1_0_
from
Student students0_
where
students0_.cid=?
-----------------------------------------
所以会去查询2次,第一次去查询指定的Team,第二次会查询指定Team下所有的Student.
使用Join fetch 是为了减少查询的次数。
----------------查询---------------------
List
for(Team t : lists){
System.out.println(t.getCid()+ " "+t.getName()+" ");
for(Student s:t.getStudents()){
System.out.println(" "+s.getId()+" "+ s.getName() +" "+s.getTeam().getCid());
}
}
----------------查询结果-----------------
Hibernate:
select
team0_.cid as cid0_0_,
students1_.id as id1_1_,
team0_.name as name0_0_,
students1_.cid as cid1_1_,
students1_.name as name1_1_,
students1_.cid as cid0_0__,
students1_.id as id0__
from
team class0_
inner join
Student students1_
on team0_.cid=students1_.cid
order by
team0_.cid
-----------------------------------------
结果发现只发错一条SQL语句。经鉴定,Join fetch 是为了用来减少查询次数的。
实质是就是使用了数据库的join.
鉴定完毕。