浅谈Hibernate中加载的三种类型

一:Hibernate实体对象的加载

比如说:用户和订单的关系是一对多,虽然它们有关联,但是默认是延迟加载Lazy=“true”,最终得到的是代理对象,如果要访问代理对象的属性的话,则会抛出异常,

解决方法:leftjoinfetch迫切抓取连接

selectufromUseruleftjoinfetchOrdero;

二:Hibernate普通属性

默认是:lazy=“false”

如果要改为延迟方法较麻烦

三:Hibernate集合对象

setlistmap默认Lazy=“true”

1:List

Java代码  



<listnamelistname="diarys"table="petDiary"cascade="all"inverse="true"> 




<keycolumnkeycolumn="petId"></key> 




<indexcolumnindexcolumn="listindex"></index> 




<one-to-manyclassone-to-manyclass="com.lovo.po.PetDiary"/> 




</list> 



 



<listnamelistname="diarys"table="petDiary"cascade="all"inverse="true"> 




  <keycolumnkeycolumn="petId"></key> 




  <indexcolumnindexcolumn="listindex"></index> 




  <one-to-manyclassone-to-manyclass="com.lovo.po.PetDiary"/> 




</list> 

2:set

Java代码  



<setnamesetname="orders" 




table="t_order" 




cascade="all" 




inverse="true" 




lazy="true" 




> 




<keycolumnkeycolumn="fk_customer_id"></key> 




<one-to-manyclassone-to-manyclass="Order"/> 




</set> 



 



<setnamesetname="orders" 




table="t_order" 




cascade="all" 




inverse="true" 




lazy="true" 




> 




<keycolumnkeycolumn="fk_customer_id"></key> 




<one-to-manyclassone-to-manyclass="Order"/> 




</set> 

3:map

Java代码  



privateMapschool=newHashMap();  



 


publicMapgetSchool(){  


returnschool;  


}  


publicvoidsetSchool(Mapschool){  



this.school=school;  



}  


 



privateMapschool=newHashMap();  



 


publicMapgetSchool(){  


returnschool;  


}  


publicvoidsetSchool(Mapschool){  



this.school=school;  



} 
Xml代码  



<mapnamemapname="school"table="schools"> 




<keycolumnkeycolumn="pid"not-null="true"/> 




<map-keytypemap-keytype="string"column="indet"/> 




<elementtypeelementtype="float"column="score"/> 




</map> 



 



privateMapschool=newHashMap();  



 


publicMapgetSchool(){  


returnschool;  


}  


publicvoidsetSchool(Mapschool){  



this.school=school;  



}  


 



privateMapschool=newHashMap();  



 


publicMapgetSchool(){  


returnschool;  


}  


publicvoidsetSchool(Mapschool){  



this.school=school;  



} 

相关推荐