一对多处理: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
用一个子查询去查询老师的数据
<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
配置
<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>