复杂的多对一SQL查询★★★★★

声明

本文为其他博主文章总结,仅用作个人学习,特此声明

参考文章链接

(3条消息) 狂神说 | Mybatis完整版笔记_小七rrrrr的博客-CSDN博客_狂神说mybatis笔记

复杂SQL查询(较难理解)

1. 按照查询嵌套处理

代码

StudentMapper.java

package com.xy.dao;

import com.xy.dao.pojo.Student;

import java.util.List;

public interface StudentMapper {
    //查找所有学生信息以及其对应的老师的信息
    public List<Student> getStudent();
}

StudentMapper.xml

<!--
思路:
1.查询所有学生的信息
2.根据查询出来学生的tid,寻找对应的老师
-->
<select id="getStudent" resultMap="student">
    select * from Mybatis.student;
</select>
<resultMap id="student" type="Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <!--复杂的属性我们需要单独处理
        \对象使用 association
        \集合使用 collection-->
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>

上面的这一段的代码有点难以理解,我们着重理解一下下面这行代码

<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>

首先我们确定它的所处位置:处于resultmap中!也就是说这一行代码是用来确定数据库字段和Student类属性的映射关系的

观察它上边的两行代码

<result property="id" column="id"/>
<result property="name" column="name"/>

我们不难知道:数据库中的id字段对应Student类中的id属性,数据库中的name字段对应Student类中的name属性

也就是说这行代码其实就是反应了一种映射关系。

但是我们的目的是让数据库中的tid字段对应一个复杂的Teacher类,这该怎么办呢?

由于tid字段对应的是一个对象Teacher,所以我们选择使用association

理解到这里,这行代码就很好理解了

这行代码的实际意思就是:

查询结果


2. 按照结果嵌套处理

<select id="getStudent" resultType="Student" resultMap="student">
    select s.id sid,s.name sname,t.name tname,t.id tid
    from mybatis.Student s,mybatis.Teacher t
    where s.tid = t.id;
</select>
<resultMap id="student" type="Student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="Teacher">
        <result property="name" column="tname"/>
        <result property="id" column="tid"/>
    </association>
</resultMap>

其实跟上边的方法一相比换汤不换药

我们还是来着重理解一下这段代码

<association property="teacher" javaType="Teacher">
    <result property="name" column="tname"/>
    <result property="id" column="tid"/>
</association>

现在我就是要将Student类的teacher这个属性对应一个字段,但是我不用嵌套查询的方法

嵌套结果

其实就是这样映射的(拆开成了两个表,表一嵌套表二)

数据库字段 Student类的属性
sid id
sname name
/ teacher
数据库字段 Teacher类的属性
tid id
tname name

其实很难理解,我反正是理解了

尽量理解!!!

查询结果

posted @ 2022-06-08 18:44  无关风月7707  阅读(179)  评论(0编辑  收藏  举报