mybatis的N+1問題

Mybatis的N+1問題主要說的是當查詢一個表的時候這個表的一個信息用外鍵鏈接另外一個表的多條信息的時候就會出現mybatis的N+1問題。這樣會導致數據庫負載過大,從而導致程序運行過慢
所以在所有的SQL語句中儘量避免該問題的出現。
如以下實例:
當查詢班級表的時候

<select id="select"  resultMap="studentResultMap">
  	select * from t_class
</select>

根據如下映射,將會調用selectStudent此查詢語句,根據外鍵c_id查詢學生信息,添加到歷實體list屬性中

<resultMap type="jee.pk2.Clazz" id="clazzResultMap">
	<id property="id" column="c_id"/>
	<result property="name" column="c_name"/>
	<association property="students" column="c_id" select="selectStudent"></association>
	<!-- 將班級的c_id傳遞給select student查詢,然後 selectStudent查詢將查詢結果賦值利用studentResultMap解析到students集合裏面-->
</resultMap>

selectStudent的查詢語句以及映射關係如下

<select id="selectStudent" parameterType="int" resultMap="studentResultMap">
  	select * from t_student where c_id=#{id}
  </select>
  
<resultMap type="jee.pk2.Student" id="studentResultMap">
	<id property="id" column="S_id" ></id>
	<result property="name" column="s_name"/>
	<result property="sno" column="s_no"/>
	<result property="gender" column="s_gender"/>
	
</resultMap>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章