MyBatis中的一对多和多对一
多对一
1.前期导入lombok依赖(也可以手动写完实体类)
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
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接口
按查询嵌套处理
1.接口中添加对应的方法,获取所有学生及对应老师的信息
public List getStudents();
编写对应的Mapper文件
association关联属性
property属性名
javaType属性类型
column在多的一方的表中的列名
<select id="getStudents" resultMap="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
当id,只有一个属性的时候,下面可以写任何值
association中column多参数配置:
column="{key=value}"
键值对的形式,key是传给下个sql的取值名称,
value是片段一中sql查询的字段名。
<select id="getTeacher" resultType="teacher">
select * from teacher where id = #{id}
</select>
按结果嵌套处理
1.先查询出结果,再进行结果集的映射
<select id="getStudents2" resultMap="StudentTeacher2" >
select s.id sid, s.name sname , t.name tname
from student s,teacher t
where s.tid = t.id
</select>
<!--关联对象property 关联对象在Student实体类中的属性-->
<resultMap id="StudentTeacher1" type="Student">
<id property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association
一对多
按结果嵌套处理
public class Student {
private int id;
private String name;
private int tid;
public class Teacher {
private int id;
private String name;
private List<Student> students;
}
从学生表和老师表中查出学生id,学生姓名,老师姓名
`对查询出来的操作做结果集映射
集合使用collection!
JavaType和ofType都是用来指定对象类型的
JavaType是用来指定pojo中属性的类型
ofType指定的是映射到list集合属性中pojo的类型。
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid, s.name sname , t.name tname, t.id tid
from student s,teacher t
where s.tid = t.id and t.id=#{id}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="name" column="tname"/>
<collection property="students" ofType="Student">
<result property="id" column="sid" />
<result property="name" column="sname" />
<result property="tid" column="tid" />
</collection>
</resultMap>
按查询嵌套处理
<select id="getTeacher1" resultMap="TeacherStudent1">
select * from teacher where id = #{id}
</select>
<resultMap id="TeacherStudent1" type="Teacher">
<!--column是一对多的外键 , 写的是一的主键的列名-->
<collection property="students" javaType="ArrayList" ofType="Student" column="id" select="getStudentByTeacherId"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid = #{id}
</select>