MyBatis 一对多处理

1.方法一

Sql较复杂 但映射逻辑简单

<select id="getTeacherList" resultMap="StudentTeacher">
select s.id sid,s.name sname,t.name tname,t.id tid
from mybatis.student s,mybatis.teacher t
where s.tid=t.id
and t.id=#{id}
</select>
    <!--集合中的泛型信息用ofType-->
    <resultMap id="StudentTeacher" type="com.wsx.domain.Teacher">
        <result property="id" column="tid"></result>
        <result property="name" column="tname"></result>
        <collection property="students" ofType="com.wsx.domain.Student">
            <result property="id" column="sid"></result>
            <result property="name" column="sname"></result>
        </collection>
    </resultMap>

2.方法二

sql简单 但映射有点绕

 <!--根据结果映射-->
    <select id="getTeacherList2" resultMap="StudentTeacher2">
        select * from mybatis.teacher where id=#{id}
    </select>
    <resultMap id="StudentTeacher2" type="com.wsx.domain.Teacher" >
        <collection property="students" column="id" javaType="ArrayList" ofType="com.wsx.domain.Student" select="getStudentByTeacher"/>
    </resultMap>
    <select id="getStudentByTeacher" resultType="com.wsx.domain.Student">
        select * from mybatis.student where tid=#{tid}
    </select>