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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章