一对多
环境模拟:
一个老师对应多个学生,要求查询一个老师,附带其所有学生
学生字段中含有老师的id
<mapper namespace="com.xiaoyu.dao.TeacherMapper">
<!--方法1:使用连接查询+结果集映射-->
<select id="queryTeacherById" resultMap="TeaStu">
select t.id tid,t.name tname,s.id sid,s.name sname
from teacher t,student s
where t.id = s.tid and t.id = #{tid};
</select>
<resultMap id="TeaStu" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--注意:ofType表示的是集合的泛型时什么-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
<!--方式2:使用子查询-->
<select id="queryTeacherById2" resultMap="TeaStu2">
select * from teacher where id = #{tid};
</select>
<resultMap id="TeaStu2" type="Teacher">
<result property="id" column="id"/>
<collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudentById"/>
</resultMap>
<select id="getStudentById" resultType="Student">
select * from student where tid=#{id};
</select>
</mapper>
推荐使用当时一,直接通过sql查出需要的所有信息,然后通过resultMap中的collection标签装配众多附属对象
多对一
场景模拟:一个老师有多个学生,要求查出所有学生极其对应的老师
接口:
List<Student> queryStudents();
映射:
<mapper namespace="com.xiaoyu.dao.StudentMapper">
<!--方式1:使用结果集映射-->
<select id="queryStudents2" resultMap="StuTea">
select s.id sid,s.name sname,t.id teid,t.name tename
from `student` s,`teacher` t
where s.tid = t.id;
</select>
<resultMap id="StuTea" type="student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="id" column="teid"/>
<result property="name" column="tename"/>
</association>
</resultMap>
<!--方式2,使用嵌套查询,类似子查询-->
<!-- ~===================================================================~ -->
<select id="queryStudents" resultMap="StudentTeacher">
select s.id sid,s.name sname,t.id teid
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" column="teid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{teid}
</select>
</mapper>
推荐使用方式一,通过association标签联系对象,对象内置字段到属性的映射
注意:
对于返回值的理解:
在设置返回值时,只需要写出返回的元返回值类型,至于时List还是bean对象,反射回自己判断!