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

目录

  • 数据准备
  • 查询嵌套处理(子查询)
  • 结果嵌套处理
  • 小结

一对多处理:https://blog.csdn.net/weixin_44953227/article/details/112789495


数据准备

数据表

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">
    
    <resultMap id="StudentTeacher" type="com.pro.pojo.Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        
        <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">
    
    <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>


小结

  1. 关联 - association 处理多对一
  2. 集合 - collection 处理一对多
  3. javaType & ofType
    1. javaType: 用来指定实体类中属性的类型
    2. ogType: 指定集合中的类型,泛型中的约束类型

你可能感兴趣的:(Java,mybatis,java)