懒加载:
Hibernate的懒加载属性,很大程度上提高了了Hibernate框架的查询效率。
lazy有三个属性:true、false、extra
【true】:默认取值,它的意思是只有在调用这个集合获取里面的元素对象时,才发出查询语句,加载其
集合元素的数据
【false】:取消懒加载特性,即在加载对象的同时,就发出第二条查询语句加载其关联集合的数据
【extra】:一种比较聪明的懒加载策略,即调用集合的size/contains等方法的时候,hibernate并不会去加载整个集合的数据,而是发出一条聪明的SQL语句,以便获得需要的值,只有在真正需要用到这些集合元素对象数据的时候,才去发出查询语句加载所有对象的数据。
举例:
lazy="true"时
配置文件中更改:<!--
配置set标签
* name :多的一方的集合的属性名称
-->
<set name="linkMans" fetch="select" lazy="true">
@Test
/**
* 在set集合上配置fetch和lazy:默认情况
* fetch="select" lazy="true"
*/
public void demo2(){
Session session = HibernateUtils.getCurrentSession();
Transaction transaction = session.beginTransaction();
Customer customer =session.get(Customer.class, 1l);
System.out.println(customer.getLinkMans().size());
transaction.commit();
}
控制台运行结果
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"时
配置文件中更改:<!--配置set标签
* name :多的一方的集合的属性名称
-->
<set name="linkMans" fetch="select" lazy="extra">
@Test
/**
* 在set集合上配置fetch和lazy:默认情况
* fetch="select" lazy="extra"
*/
public void demo2(){
Session session = HibernateUtils.getCurrentSession();
Transaction transaction = session.beginTransaction();
Customer customer =session.get(Customer.class, 1l);
System.out.println(customer.getLinkMans().size());
transaction.commit();
}
控制台运行结果:
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的查询效率。我们项目实际开发中并不会太区分这些东西,只要把功能实现即可。但是一个好的开发习惯,要求我们尽量做到更好的优化,所以了解这些东西对初学者培养优秀开发习惯有很大帮助。一些外企从代码算法上会有很多要求,所以一个好的代码思维习惯对以后进入更高层次公司还是有很大帮助的。