其他分享
首页 > 其他分享> > Mybatis-part11一对多

Mybatis-part11一对多

作者:互联网

11、一对多

比如:一个老师拥有多个学生!

对于老师而言,一对多的关系

1.搭建环境

实体类

@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}
@Data
public class Teacher {
    private int id;
    private String name;

    //一个老师有多个学生
    private List<Student> student;
}

按照查询嵌套处理(子查询)

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

    <resultMap id="TeacherStudent2" type="Teacher">
        <collection property="students" ofType="Student" select="getStudentByTeacherId" column="id">
        </collection>
    </resultMap>
    <select id="getStudentByTeacherId" resultType="Student">
        select * from student where tid =#{tid};
    </select>
</mapper>

按照结果嵌套处理(连表查询)

	<select id="getTeacher" resultMap="TeacherList">
        select t.name tname,t.id tid,s.id sid,s.name sname
        from teacher t,student s
        where s.tid=t.id and tid=#{tid};
    </select>
    <resultMap id="TeacherList" type="Teacher">
        <result property="id" column="tid"></result>
        <result property="name" column="tname"></result>
       <collection property="students" ofType="Student">
           <result property="id" column="sid"></result>
           <result property="name" column="sname"></result>
           <result property="tid" column="tid"></result>
       </collection>
    </resultMap>

小结

  1. 关联-association【多对一】
  2. 集合-collection【一对多】
  3. javaType & ofType
    1. javaType用来指定实体类中属性的类型
    2. ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束条件

注意点:

面试高频

标签:name,int,part11,private,tid,Mybatis,一对,id,select
来源: https://blog.csdn.net/qq_56594964/article/details/121362658