Mybatis 实现一对多关系

实体类

//teacher 类
    private int id;
   private String name;
    // 一个老师有多个学生 集合
   private List<Student> students;

// student 类
    private int id;
   private String name;
   private int tid;

按照结果嵌套处理

  <select id="getTeacher" resultMap="TeacherMap">
        select s.id sid,s.name sname,t.name tname,t.id tid
        from student s,teacher t
        where t.id = s.tid
        and t.id = #{tid};
  </select>

  <resultMap id="TeacherMap" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--javaType 指定属性的类型; 集合中的泛型,使用oftype获取 集合使用 collection 处理-->
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
        </collection>
  </resultMap>

按查询嵌套处理

    <select id="getTeacher2" resultMap="TeacherMap2">
        select * from teacher where id = #{tid}
   </select>

   <resultMap id="TeacherMap2" type="Teacher">
        <collection property="students" javaType="ArrayList" ofType="Student" column="id" select="getStudentByTeacherID"/>
   </resultMap>

   <select id="getStudentByTeacherID" resultType="Student">
        select * from student where tid = #{tid}
   </select>