这是我在 MySQL 中直接查询的结果:

image

一共有 4 条数据。

这是 MyBatis 查询出来的结果:

image

查询出来只有 2 条数据,这和我在 MySQL 中直接查询的数量严重不一致。在网上也查询了好多资料,他们的情况与我的情况都不一样。经过我自己的查询和试错,发现是因为我的 resultMap 开启了 autoMapping,且我多余地添加了子标签 result,所以导致最终查询的数量不一致。

下面是错误的 resultMap 映射操作:

<resultMap id="mapOfQueryMyCourses" type="UniCourse" autoMapping="true">
  <result column="term" property="term"/>
  <association property="course" javaType="Course" columnPrefix="c_" autoMapping="true"/>
  <association property="teacher" javaType="Teacher" columnPrefix="t_" autoMapping="true"/>
</resultMap>
<select id="queryMyCourses" resultMap="mapOfQueryMyCourses" parameterType="Student">
  SELECT sc.term,
         sc.stu_id,
         c.name     c_name,
         c.property c_property,
         c.credit   c_credit,
         t.name     t_name
  FROM `stu_course` AS sc
         JOIN `courses` AS c ON sc.course_id = c.cno
         JOIN `teachers` AS t ON sc.teacher_id = t.tno
  WHERE sc.stu_id = #{sno}
</select>

正如上面说到的,如果开启了 autoMapping,且你的配置文件又开启了自动映射驼峰命名,就不要多余地添加子标签 result:

下面是正确地 resultMap 映射操作:

<resultMap id="mapOfQueryMyCourses" type="UniCourse" autoMapping="true">
  <association property="course" javaType="Course" columnPrefix="c_" autoMapping="true"/>
  <association property="teacher" javaType="Teacher" columnPrefix="t_" autoMapping="true"/>
</resultMap>
<select id="queryMyCourses" resultMap="mapOfQueryMyCourses" parameterType="Student">
  SELECT sc.term,
         sc.stu_id,
         c.name     c_name,
         c.property c_property,
         c.credit   c_credit,
         t.name     t_name
  FROM `stu_course` AS sc
         JOIN `courses` AS c ON sc.course_id = c.cno
         JOIN `teachers` AS t ON sc.teacher_id = t.tno
  WHERE sc.stu_id = #{sno}
</select>

即,删除掉多余的 result 子标签,association 也不需要写。如下图所示,这下查询出来的数量就保持一致了:

image