組織機構是一顆樹型機構,乙個父類對應多個子類。該物件的xml檔案為
機構名稱
職能描述
部門**
排序號形成機構樹時,需要查詢出所有節點,並且會根據節點來獲取子節點。所以應該採用即時抓取。
方法一:設定lazy為false 也就是即時抓取
使用gethibernatetemplate().loadall(organization.class);能達到目的但會發出n+1條sql語句
select
this_.id as id0_0_,
this_.organization_name as organiza2_0_0_,
this_.description as descript3_0_0_,
this_.pid as pid0_0_,
this_.organization_tel as organiza5_0_0_,
this_.order_num as order6_0_0_
from
g_organization this_
hibernate:
select
childern0_.pid as pid1_,
childern0_.id as id1_,
childern0_.id as id0_0_,
childern0_.organization_name as organiza2_0_0_,
childern0_.description as descript3_0_0_,
childern0_.pid as pid0_0_,
childern0_.organization_tel as organiza5_0_0_,
childern0_.order_num as order6_0_0_
from
g_organization childern0_
where
childern0_.pid=?
order by
childern0_.order_num
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
第一條sql查詢出所有記錄,接下來會發出n條記錄來獲取所有相關的子記錄。查詢時間大概
20:26:18,105 info organizationbotest:51 - *******發費時間******203
所以可以看出這種方式並不是最佳選擇。
方法二: 設定抓取策略fetch="join" 並loadall時只傳送一條sql語句 fetch="join"只對load和get方法 還有就是條件查詢會起作用,而對hsql的查詢是不會有影響的
select
this_.id as id0_1_,
this_.organization_name as organiza2_0_1_,
this_.description as descript3_0_1_,
this_.pid as pid0_1_,
this_.organization_tel as organiza5_0_1_,
this_.order_num as order6_0_1_,
childern2_.pid as pid3_,
childern2_.id as id3_,
childern2_.id as id0_0_,
childern2_.organization_name as organiza2_0_0_,
childern2_.description as descript3_0_0_,
childern2_.pid as pid0_0_,
childern2_.organization_tel as organiza5_0_0_,
childern2_.order_num as order6_0_0_
from
g_organization this_
left outer join
g_organization childern2_
on this_.id=childern2_.pid
order by
childern2_.order_num
發費時間大概為
20:28:01,450 info organizationbotest:51 - ********發費時間*****178
但存在乙個問題就是,對於許多其他查詢應用可能不會操作子記錄,也就沒有立即抓取子節點的必要,而且這樣會浪費記憶體。
hibernate 一對多(多對一)
舉個例子 乙個國家有多個省份,多個省份只有乙個國家,這個就是多對一和一對多,兩者就是看物件的角度問題 多對一關聯對映 在多的一端加入外來鍵指向一的一端,他維護的關係是多指向一 一對多關聯對映 在多的一端加入外來鍵指向一的一端,它維護的關係是一指向多 也就是說一對多和多對一的對映策略是一樣的,只是站的...
hibernate註解一對多 多對一
註解 多對一刪除時 只執行多的一方而一不會改變 新增時考慮 一的一方主鍵是否存在 cascade表示級聯操作 cascadetype.merge級聯更新 cascadetype.persist級聯重新整理 cascadetype.refresh級聯儲存 cascadetype.remove級聯刪除 ...
Hibernate一對多 雙向
hibernate 雙向關聯就是有 一對多 和 多對一 兩個關聯組合而成德,在雙向關聯的兩端都知道對方是誰。下面就開始演示這種關聯。首先定義我們需要使用的pojo物件。public class member public class order 兩個pojo對應的對映檔案分別為member.hbm....