蘇阿細 - 关联
type: channel
link: https://www.wangchouchou.com/tag/%E5%85%B3%E8%81%94/
items: 多对一

多对一
type: item
date: 2020-12-13T14:10:00+00:00
description: 多对一处理多对一：多个学生对应一个老师对学生而言：关联，关联一个老师【多对一】对老师而言，集合，一个老师有很多学生【一对多】Demo实例：CREATE TABLE `teacher`( `id` int(11) NOT NULL, `name` VARCHAR(50) DEFAULT NULL, PRIMARY KEY (id) )ENGINE=INNODB DEFAULT CHARSET=utf8; INSERT INTO teacher(`id`,`name`) VALUES(1,'孙笑川'); CREATE TABLE `student`( `id` int(11) NOT NULL, `name` VARCHAR(50) DEFAULT NULL, `tid` int(11) 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);测试环境搭建：1、导入Lombok2、新建实体类Teacher，Student3、建立Mapper接口4、建立Mapper.xml5、在mybatis-config.xml核心配置文件中注册绑定接口6、测试查询是否成功按照嵌套查询处理： select * from student; <result property="id" column="id"/> <result property="name" column="name"/> select * from teacher where id = #{id}; 按照结果嵌套处理： select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid = t.id; <result property="id" column="sid"/> <result property="name" column="sname"/> <result property="name" column="tname"/>