多对一&一对多

9、多对一处理

  • 多个学生,对应一个老师
  • 对于学生而言,关联,多个学生,关联一个老师【多对一】
  • 对于老师而言,集合,一个老师,有很多学生【一对多】

测试环境搭建

1.新建实体类Teacher,Student

public class Student {

  private long id;
  private String name;
  private long tid;
  private Teacher teacher;

2.建立Mapper接口

3.建立Mapper.xml

4.在核心配置文件中绑定Mapper接口或者文件【方式多】

5.测试查询是否能够成功

按照查询嵌套处理

    <select id="getStudent" resultMap="StudentTeacher">
        select * from student;
    </select>
    <resultMap id="StudentTeacher" type="Student">
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <!--复杂的属性,我们需要单独处理
            对象:association
            集合:collection
        -->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>
    <select id="getTeacher" resultType="com.pireua.pojo.Teacher">
        select * from teacher where id=#{id};
    </select>

按照结果嵌套处理

<!--    按照结果嵌套处理-->
    <select id="getStudent1" resultMap="StudentTeacher1">
        select s.id sid,s.name sname,t.name tname
        from student s,teacher t
        where s.tid =t.id
    </select>
    <resultMap id="StudentTeache1r" type="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

回顾Mysql多对一查询方式:

  • 子查询
  • 联表查询

10、一对多处理

环境搭建

public class Teacher {

  private long id;
  private String name;
  private List<String> student;

按照结果集映射嵌套处理

    <select id="getTeacher" resultMap="TeacherStudent">
    select s.id sid,s.name sname,t.name tname,t.id tid
from teacher t,student s
where t.id=s.tid and t.id=#{tid};
</select>
    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--复杂的属性,我们需要单独处理对象:association集合:collection
        javaType指定属性的类型
        ofType指定集合中泛型的类型
        -->
        <collection property="student" ofType="Student" >
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>

小结

1.关联 -association【多对一】

2.集合 -collection【一对多】

3.javaType & ofType

​ 1、javaType用来指定实体类中属性的类型

​ 2、ofType用来指定映射到List或者集合中pojo类型,泛型中的约束类型!

注意点:

  • 保证SQL的可读性,尽量保证通俗易懂
  • 注意一对多和多对一中,属性和字段的问题
  • 如果问题不好排查,可以使用日志,建议使用Log4j

面试高频

  • Mysql引擎
  • InnoDB底层原理
  • 索引
  • 索引优化
posted @ 2021-09-08 16:06  Pireua  阅读(64)  评论(0)    收藏  举报