天天看點

lazy與fetch

筆記:

<class name="Student" table="student" >
		<id name="studentNO" type="int">
			<generator class="native"></generator>
		</id>
		<property name="studentName" type="string"/>
		<many-to-one name="classes" column="classNO" class="Classes" fetch="join" lazy="false"></many-to-one>
	</class>
           

 當用load方法加載Student時,會延時加載

當不設fetch=join用lazy=true時:

對于many-to-one,one-to-one,集合如component,set,map,array,list這些本身預設lazy=true的屬性,不管是load還是get,表現出來的都是使用classes時才加載,看上去get在這裡也是延時加載了,可見延不延時加載在此時隻是針對目前對象的普通屬性。但是當lazy=false時,這些屬性,不管是load還是get都是都是同時發出兩條sql,盡管load方法是在使用目前對象時才發出sql,而get是在一執行時就發出2條sql。

當設fetch=join時

查詢student時,會同時查出classes,而且是通過一條連接配接查詢實作,這個時候集合屬性裡面的lazy就沒有作用了。

對于load會在使用student或classes時,發出sql,對于get會在執行進就發出sql

  • Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT , using an OUTER JOIN .用外連接配接檢索相關的執行個體或集合,通過一條select語句(實了下,發現是左外連接配接)
  • Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false" , this second select will only be executed when you actually access the association.通過第二條select語句檢索相關的實體或集合,但是前提lazy=false,并且隻有在通路相關資料時才會發出第二條sql