hibernate join fetch
那天去了達內,試聽了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<Student> students;
get{…}; set{…}';
}
默認查詢Team 的時候,fetch=lazy,不會去查詢 Team 中所有的Student.
----------------查詢---------------------
Team t=(Team)session.load(Team.class, 3);
??????? Set<Student> sets=t.getStudents();
??????? 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<Class> lists = session.createQuery("from Team t? join fetch c.students order by t.cid").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.
鑒定完畢。
轉載于:https://www.cnblogs.com/huangjingzhou/articles/1876213.html
總結
以上是生活随笔為你收集整理的hibernate join fetch的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 原神喂猫成就怎么做?
- 下一篇: blog地址: