我已經樣品實體表A表B和在表A中,我們有註釋爲波紋管柱TABLE_B_ID:休眠標準OneToOne FetchType.Eager FetchMode.Join執行不必要queryes
@OneToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "TABLE_B_ID")
@Fetch(FetchMode.JOIN)
然後,當我執行這樣簡單的代碼:
Criteria c = session.createCriteria(TableA.class);
c.list();
爲N + 1次,其中n =數的排TableA中,即使表A已經與表B第一查詢joinned,休眠還是試圖通過另一種選擇,以獲得表B每個Hibernate的運行查詢查詢。
查詢觸發:
Hibernate:
select
this_.id as id1_0_1_,
this_.name as name2_0_1_,
this_.TABLE_B_ID as TABLE_B_3_0_1_,
tableb2_.id as id1_1_0_,
tableb2_.name as name2_1_0_
from
TABLE_A this_
inner join
TABLE_B tableb2_
on this_.TABLE_B_ID=tableb2_.id
Hibernate:
select
tablea0_.id as id1_0_1_,
tablea0_.name as name2_0_1_,
tablea0_.TABLE_B_ID as TABLE_B_3_0_1_,
tableb1_.id as id1_1_0_,
tableb1_.name as name2_1_0_
from
TABLE_A tablea0_
inner join
TABLE_B tableb1_
on tablea0_.TABLE_B_ID=tableb1_.id
where
tablea0_.TABLE_B_ID=?
Hibernate:
select
tablea0_.id as id1_0_1_,
tablea0_.name as name2_0_1_,
tablea0_.TABLE_B_ID as TABLE_B_3_0_1_,
tableb1_.id as id1_1_0_,
tableb1_.name as name2_1_0_
from
TABLE_A tablea0_
inner join
TABLE_B tableb1_
on tablea0_.TABLE_B_ID=tableb1_.id
where
tablea0_.TABLE_B_ID=?
等..
我已經嘗試刪除FetchMode
或更改optional=true
但解僱查詢仍然是N + 1次。 甚至在他已經獲得第一個select查詢中的數據之後,hibernate發射另一個select的原因是什麼?
您是否嘗試過使用FetchType.LAZY – Jens
我想急於加載 – Angga
您是否嘗試過使用內部/外部連接!可能是tableB比tableA多一行。 –