Hibernate lazy的三種屬性

2021-07-24 06:57:33 字數 2641 閱讀 9277

懶載入:

hibernate的懶載入屬性,很大程度上提高了了hibernate框架的查詢效率。

lazy有三個屬性:true、false、extra

【true】:預設取值,它的意思是只有在呼叫這個集合獲取裡面的元素物件時,才發出查詢語句,載入其 

集合元素的資料

【false】:取消懶載入特性,即在載入物件的同時,就發出第二條查詢語句載入其關聯集合的資料 

【extra

】:一種比較聰明的懶載入策略,即呼叫集合的size/contains等方法的時候,hibernate並不會去載入整個集合的資料,而是發出一條聰明的sql語句,以便獲得需要的值,只有在真正需要用到這些集合元素物件資料的時候,才去發出查詢語句載入所有物件的資料。

舉例:lazy="true"時

配置檔案中更改:

@test

/*** 在set集合上配置fetch和lazy:預設情況

* fetch="select" lazy="true"

*/public void demo2()

控制台執行結果

hibernate:

select

customer0_.cust_id as cust_id1_0_0_,

customer0_.cust_name as cust_nam2_0_0_,

customer0_.cust_source as cust_sou3_0_0_,

customer0_.cust_industry as cust_ind4_0_0_,

customer0_.cust_level as cust_lev5_0_0_,

customer0_.cust_phone as cust_pho6_0_0_,

customer0_.cust_mobile as cust_mob7_0_0_

from

cst_customer customer0_

where

customer0_.cust_id=?

hibernate:

select

linkmans0_.lkm_cust_id as lkm_cus10_1_1_,

linkmans0_.lkm_id as lkm_id1_1_1_,

linkmans0_.lkm_id as lkm_id1_1_0_,

linkmans0_.lkm_name as lkm_name2_1_0_,

linkmans0_.lkm_gender as lkm_gend3_1_0_,

linkmans0_.lkm_phone as lkm_phon4_1_0_,

linkmans0_.lkm_mobile as lkm_mobi5_1_0_,

linkmans0_.lkm_email as lkm_emai6_1_0_,

linkmans0_.lkm_qq as lkm_qq7_1_0_,

linkmans0_.lkm_position as lkm_posi8_1_0_,

linkmans0_.lkm_memo as lkm_memo9_1_0_,

linkmans0_.lkm_cust_id as lkm_cus10_1_0_

from

cst_linkman linkmans0_

where

linkmans0_.lkm_cust_id=?10

lazy="extra"時

配置檔案中更改:

@test

/*** 在set集合上配置fetch和lazy:預設情況

* fetch="select" lazy="extra"

*/public void demo2()

控制台執行結果:

hibernate:

select

customer0_.cust_id as cust_id1_0_0_,

customer0_.cust_name as cust_nam2_0_0_,

customer0_.cust_source as cust_sou3_0_0_,

customer0_.cust_industry as cust_ind4_0_0_,

customer0_.cust_level as cust_lev5_0_0_,

customer0_.cust_phone as cust_pho6_0_0_,

customer0_.cust_mobile as cust_mob7_0_0_

from

cst_customer customer0_

where

customer0_.cust_id=?

hibernate:

select

count(lkm_id)

from

cst_linkman

where

lkm_cust_id =?10

【小結】

懶人思想,extra能夠更高效能的提公升hibernate的查詢效率。我們專案實際開發中並不會太區分這些東西,只要把功能實現即可。但是乙個好的開發習慣,要求我們盡量做到更好的優化,所以了解這些東西對初學者培養優秀開發習慣有很大幫助。一些外企從**演算法上會有很多要求,所以乙個好的**思維習慣對以後進入更高層次公司還是有很大幫助的。

hibernate lazy 延遲載入

hibernate lazy策略可以使用在 標籤上,可以取值 true false 在hibernate3以上版本,預設是true 標籤上,可以取值 true false 需要類增強工具 標籤上,可以取值 true false extra 單端關聯上,可以取值 false proxy no prox...

hibernate lazy 延遲載入

hibernate lazy策略可以使用在 標籤上,可以取值 true false 在hibernate3以上版本,預設是true 標籤上,可以取值 true false 需要類增強工具 標籤上,可以取值 true false extra 單端關聯上,可以取值 false proxy no prox...

HIbernate Lazy 常用配置

lazy 延遲載入,在真正使用某個物件的時候才正真的去建立,即hibernate才會正真的發出sql語句去載入該物件 lazy的有效期 只有在session開啟的時候才有效 session關閉後lazy就沒效了。lazy策略可以用在 1 標籤上 可以取值true false 標籤上,可以取值true...