多对一:
多个学生,对应一个老师
对于学生而言,关联 多个学生关联一个老师 【多对一】
对于老师而言,集合 一个老师有很多学生【一对多】
SQL:
CREATE TABLE `teacher`(
`id` INT(10) NOT NULL,
`name` VARCHAR (30),
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');
1.导入Lombok
org.projectlombok
lombok
1.18.10
2.新建实体类Teacher,Student
@Data
public class Teacher {
private int id;
private String name;
}
@Data
public class Student {
private int id;
private String name;
//学生关联一个老师
private Teacher teacher;
}
3.建立Mapper接口
public interface TeacherMapper {
@Select("select * from teacher where id = #{tid}")
Teacher geyTeacher(@Param("tid")int id);
}
public interface StudentMapper {
}
4.建立Mapper.XML文件
5.在核心配置文件中绑定注册接口或文件
6.测试查询是否能成功
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.geyTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
查询所有的学生信息以及对应老师的信息
查询所有的学生信息以及对应老师的信息