MyBatis 查询数据时属性中多对一的问题(多条数据对应一条数据)

数据准备

数据表

CREATE TABLE `teacher`(
  id INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=INNODB DEFAULT CHARSET=utf8;


INSERT INTO `teacher`(id,`name`) VALUES(1,'大师');

CREATE TABLE `student`(
  id INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  `tid` INT(10) DEFAULT NULL,
  PRIMARY KEY(id),
  KEY `fktid` (`tid`),
  CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO student(`id`,`name`,`tid`) VALUES(1,'小明',1);
INSERT INTO student(`id`,`name`,`tid`) VALUES(2,'小红',1);
INSERT INTO student(`id`,`name`,`tid`) VALUES(3,'小张',1);
INSERT INTO student(`id`,`name`,`tid`) VALUES(4,'小李',1);
INSERT INTO student(`id`,`name`,`tid`) VALUES(5,'小王',1);

Teacher 类

public class Teacher {
    private int id;
    private String name;
}

Student 类

public class Student {
    private int id;
    private String name;

    private Teacher teacher;
}

查询接口

public interface StudentMapper {
    // 查询嵌套处理 - 子查询
    List<Student> getStudentList();

    // 结果嵌套处理
    List<Student> getStudentResult();
}


查询嵌套处理(子查询)

思路:先查询出所有学生的数据,再根据学生中关联老师的字段 tid 用一个子查询去查询老师的数据

  • association:处理对象
    • property:实体类中属性字段
    • column:查询结果中需要传递给子查询的字段
    • javaType:指定属性的类型
    • select:子查询SQL
<mapper namespace="com.pro.dao.StudentMapper">
    <!--
    按照查询嵌套处理
        1. 先查询所有学生信息
        2. 根据查询出来学生的tid, 接一个子查询去查老师
    -->
    <resultMap id="StudentTeacher" type="com.pro.pojo.Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--复杂属性需要单独处理, 对象: association, 集合: collection -->
        <association property="teacher" column="tid" javaType="com.pro.pojo.Teacher" select="getTeacher"/>
    </resultMap>

    <select id="getStudentList" resultMap="StudentTeacher">
        select * from student
    </select>

    <select id="getTeacher" resultType="com.pro.pojo.Teacher">
        select * from teacher where id = #{id}
    </select>
</mapper>


结果嵌套处理

思路:先把所有的信息一次性查询处理, 然后配置字段对应的实体类, 使用 association 配置

  • association:处理对象
    • property:实体类中属性字段
    • javaType:指定属性的类型
<mapper namespace="com.pro.dao.StudentMapper">
    <!--
    按照结果嵌套处理
        1. 一次查询出所有学生和老师的数据
        2. 根据查询的结果配置 association 对应的属性和字段
    -->
    <resultMap id="StudentResult" type="com.pro.pojo.Student">
        <result column="sid" property="id"/>
        <result column="sname" property="name"/>
        <!--  根据查询出来的结果, 去配置字段对应的实体类  -->
        <association property="teacher" javaType="com.pro.pojo.Teacher">
            <result column="tname" property="name"/>
        </association>
    </resultMap>

    <select id="getStudentResult" resultMap="StudentResult">
        SELECT s.id sid, s.name sname, t.name tname FROM student s, teacher t WHERE s.tid = t.id
    </select>
</mapper>
posted @ 2021-01-18 16:17  jiawei3998  阅读(205)  评论(0编辑  收藏  举报