1、什么是多对一
顾名思义,多对一即多个对象对应一个对象,这里我们用多个学生对应一个老师来举例
2、实际操作
2.1、创建学生表 student,和老师表 teacher
学生表
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');
老师表
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, '狄仁杰');
2.2、编写实体类(使用lombok实现各种构造器和getset方法)
Student类
package com.study.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private int id;
private String name;
//学生关联一个老师
private Teacher teacher;
}
Teacher类
package com.study.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher {
private int id;
private String name;
}
2.3、编写mapper接口和mapper.xml文件
StudentMapper
package com.study.dao;
import com.study.pojo.Student;
import java.util.List;
public interface StudentMapper {
// 查询所有的学生信息,以及对应的老师信息
public List<Student> getStudent();
public List<Student> getStudent2();
}
TeacherMapper
package com.study.dao;
import com.study.pojo.Teacher;
public interface TeacherMapper {
public Teacher getTeacher();
}
3、查询方式
共有两种查询方式:按照查询嵌套处理和按照结果嵌套处理
3.1、按查询嵌套处理
<select id="getStudent" resultMap="StudentTeacher">
select *
from student
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--
复杂的属性,我们需要单独处理:
对象:association
集合:collection
-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select *
from teacher
where id = #{tid}
</select>
由于teacher是一个对象,因此不能直接作为参数传递,需要使用association标签单独处理。
3.2、按结果嵌套处理
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname
from student s,teacher t
where s.tid=t.id
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>