(十二)一对多的关系
通过老师查找到自己的学生。
和上一篇比较像,因此只粘贴Mapper.xml文件,主要是其中的思想比较重要,其实数据库字段是什么不重要。
大家看着理解,还是比较有意思的。
直接进行联表查询
<select id="getTeacher" resultType="top.zhang.pojo.Teacher">
select * from teacher
</select>
<select id="getTeacherById" resultMap="teacherstudent">
select t.id tid,t.name tname,s.id sid,s.name sname
from teacher t,student s
where t.id = s.tid and tid = #{tid}
</select>
<resultMap id="teacherstudent" type="top.zhang.pojo.Teacher">
<result property="id" column="tid"></result>
<result property="name" column="t.name"></result>
<collection property="students" ofType="top.zhang.pojo.Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
</collection>
</resultMap>
使用结果进行查询
<select id="getTeacherById2" resultMap="teacherstudent2">
select *
from teacher
where id = #{tid}
</select>
<resultMap id="teacherstudent2" type="top.zhang.pojo.Teacher">
<collection property="students" column="id" ofType="top.zhang.pojo.Student" select="getStudent"></collection>
</resultMap>
<select id="getStudent" resultType="top.zhang.pojo.Student">
select *
from student
where tid = #{id}
</select>
一对多种可能比上一篇多对一稍微难一点,但是基本思路是一样的,多看几遍代码会有收获!