方式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>