lidaye2396

博客园 首页 新随笔 联系 订阅 管理

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多对一查询方式:

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

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

posted on 2021-04-08 11:11  lidaye2396  阅读(20)  评论(0编辑  收藏  举报