zoukankan      html  css  js  c++  java
  • 4月8日

    10、多对一处理

    多个学生一个老师;

    alter table student ADD CONSTRAINT fk_tid foreign key (tid) references teacher(id)
    1

    1. 测试环境搭建

    1. 导入lombok

    2. 新建实体类Teacher,Student

    3. 建立Mapper接口

    4. 建立Mapper.xml文件

    5. 在核心配置文件中绑定注册我们的Mapper接口或者文件 【方式很多,随心选】

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

    2. 按照查询嵌套处理

    <!--
        思路:
           1. 查询所有的学生信息
           2. 根据查询出来的学生的tid寻找特定的老师 (子查询)
       -->
    <select id="getStudent" resultMap="StudentTeacher">
      select * from student
    </select>
    <resultMap id="StudentTeacher" type="student">
       <result property="id" column="id"/>
       <result property="name" column="name"/>
       <!--复杂的属性,我们需要单独出来 对象:association 集合:collection-->
       <collection property="teacher" column="tid" javaType="teacher" select="getTeacher"/>
    </resultMap>
    <select id="getTeacher" resultType="teacher">
      select * from teacher where id = #{id}
    </select>
    1234567891011121314151617

    3.按照结果嵌套处理

       <!--按照结果进行查询-->
       <select id="getStudent2" resultMap="StudentTeacher2">
          select s.id sid , s.name sname, t.name tname
          from student s,teacher t
          where s.tid=t.id
       </select>
       <!--结果封装,将查询出来的列封装到对象属性中-->
       <resultMap id="StudentTeacher2" type="student">
           <result property="id" column="sid"/>
           <result property="name" column="sname"/>
           <association property="teacher" javaType="teacher">
               <result property="name" column="tname"></result>
           </association>
       </resultMap>
    1234567891011121314

    回顾Mysql多对一查询方式:

      • 子查询 (按照查询嵌套)

      • 联表查询 (按照结果嵌套)

  • 相关阅读:
    BZOJ2962: 序列操作
    BZOJ2037: [Sdoi2008]Sue的小球
    LOJ#2537. 「PKUWC2018」Minimax
    LOJ#2538. 「PKUWC2018」Slay the Spire
    BZOJ4756 [USACO17JAN]Promotion Counting晋升者计数
    BZOJ2212——线段树合并
    atcoder.keyence2019.contest E-Connecting Cities
    [转载]笛卡尔树
    大数模板
    点分治
  • 原文地址:https://www.cnblogs.com/ldy2396/p/14909237.html
Copyright © 2011-2022 走看看