上海专业制作网站莱芜最新
mybatis05:复杂查询:(多对一,一对多)
文章目录
- mybatis05:复杂查询:(多对一,一对多)
 - 前言:
 - 多对一 : 关联 : 使用association
 - 一对多 : 集合: 使用collection
 - sql语句分析:
 
- 一、多对一:student 对 teacher
 - 1.按照查询嵌套处理:与子查询很相似
 - 2.按照结果嵌套处理(推荐自己使用)
 
- 二、一对多:teacher对student
 - 1. 写sql难,但写resultMap简单。(推荐自己使用)
 - 2. 写sql简单,但写resultMap难。
 
- 总结
 
前言:
多对一 : 关联 : 使用association

一对多 : 集合: 使用collection

sql语句分析:



提示:以下是本篇文章正文内容:
一、多对一:student 对 teacher
1.按照查询嵌套处理:与子查询很相似
    <!--思路:1. 查询所有的学生2. 根据查询出来的tid 寻找对应的老师--><select id="getStudent" resultMap="StudentTeacher">select * from student</select><resultMap id="StudentTeacher" type="com.zhu.pojo.Student"><result property="id" column="id"/><result property="name" column="name"/><!--复杂的属性与要单独处理 对象 association  集合 collection--><association property="teacher" column="tid" javaType="com.zhu.pojo.Teacher" select="getTeacher"/>   </resultMap><select id="getTeacher" resultType="com.zhu.pojo.Teacher">select * from teacher where id = #{id}</select>
 
1.select标签,将resultType修改为resultMap,那么我们就需要写一个resultMap标签来映射(ORM)
2.多的一方 与 一的一方,student 与 teacher的关系是“关联”(association),这里是复杂查询的部分了,我们运用子查询的思想,根据tid来再去查询teacher对象。
2.按照结果嵌套处理(推荐自己使用)
    <!-- 思路:1.我们正常写sql语句(联表查询),2.但是对结果集映射里面的teacher对象,他的属性“再映射一次” --><select id="getStudent2" resultMap="StudentTeacher2">select s.id sid,s.name sname,t.name tnamefrom student s ,teacher twhere s.tid = t.id;</select><resultMap id="StudentTeacher2" type="com.zhu.pojo.Student"><result property="id" column="sid"/><result property="name" column="sname"/><association property="teacher" javaType="com.zhu.pojo.Teacher"><result property="name" column="tname"/></association></resultMap>
 
1.resultType修改为resultMap
2.我们对查询结果中的类,在映射一遍
二、一对多:teacher对student
1. 写sql难,但写resultMap简单。(推荐自己使用)
<!--  按结果嵌套查询-->
<select id="getTeacher" resultType="com.zhu.pojo.Teacher">select * from teacher;
</select>
<select id="GetTeacher" resultMap="GetStudent">select s.id sid ,s.name sname ,t.name tname,t.id tidfrom student s,teacher twhere s.tid = t.id and t.id=#{tid}
</select>
<resultMap id="GetStudent" type="com.zhu.pojo.Teacher"><result property="id" column="tid"/><result property="name" column="tname"/>
<!--
javaType="" 指定的属性的类型
集合中的泛型信息用 ofType 获取
--><collection property="students" ofType="com.zhu.pojo.Student"><result property="id" column="sid"/><result property="name" column="sname"/><result property="tid" column="tid"/></collection>
</resultMap>
 
2. 写sql简单,但写resultMap难。
<!--先查询老师,再查学生-->
<select id="GetTeacher2" resultMap="GetStudent2">select *from teacher where id=#{tid}
</select>
<resultMap id="GetStudent2" type="com.zhu.pojo.Teacher"><collection property="students"  javaType="ArrayList" ofType="com.zhu.pojo.Student" select="GetStudentByTeacherId" column="id"/>
</resultMap>
<select id="GetStudentByTeacherId" resultType="com.zhu.pojo.Student">select *from student where tid = #{tid}
</select>
 
总结
提示:这里对文章进行总结:
💕💕💕
重点:推荐使用 写sql难一点,但写resultMap简单一点的方法
(完完整整将语句语句给写完!!!)
