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>

《Mybatis 实现一对多关系》有5个想法

  1. There are a few things us guys would rather do, like sorting a box of mixed nails, screws, bolts, washers and nuts into little sliding drawers of a box bought at Home Depot! Keelia Forster Tavis

  2. Nice post. I learn something new and challenging on blogs I stumbleupon every day. It will always be exciting to read through content from other writers and use something from other websites. Faustine Nikolaus Ming

  3. Someone necessarily help to make severely articles I might state. This is the first time I frequented your website page and to this point? I amazed with the analysis you made to make this actual post amazing. Excellent activity! Analise Arnoldo Zumwalt

发表评论

邮箱地址不会被公开。 必填项已用*标注