方式1:按照结果集嵌套
就是先把所需要的数据查询出来,再做映射。
<select id="getStudent" resultMap="StudentTeacher">
select s.id sid,s.name sname,t.name tname,s.tid stid
from student s,teacher t
where s.tid = t.id
</select>
<resultMap id="StudentTeacher" type="student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
<result property="id" column="stid"/>
</association>
</resultMap>
方式2:按照查询嵌套处理
思路:先查主表,再通过关联建(外键)查询子表
例如下面代码:先查询学生所有信息,再通过tid(老师id)查询老师的信息。
<select id="getStudent2" resultMap="StudentTeacher2">
select * from student
</select>
<resultMap id="StudentTeacher2" type="student" >
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{tid}
</select>
本文探讨了MyBatis中处理数据映射的两种方法:结果集嵌套和查询嵌套。结果集嵌套是在查询时直接将所需字段组合,而查询嵌套则是先查询主表,再通过外键获取关联表信息。这两种方式各有优缺点,适用于不同的场景,对于理解和优化数据库查询效率有重要意义。
2349

被折叠的 条评论
为什么被折叠?



