Mybatis一对多和多对一处理

本文示例

使用学生和老师的对应关系举例

  • 老师的角度:一个学科老师对应多个学生,一对多
  • 学生的角度:多个学生对应一个学科老师,多对一

一对多

实体类创建

因为是从老师的角度来看,一个老师对应多个学生,所以学生实体类正常创建
老师的实体类中增加 private List<Student> students;的对应关系

映射*Mapper.xml

老师的查询结果集<resultMap>中,增加<collection>标签设置学生对应属性

1
2
3
4
5
6
7
8
9
<resultMap id="TeacherToStudent" type="Teacher">
<result property="id" column="tid"/> <!-- 老师的id -->
<result property="name" column="tname"/> <!-- 老师的名字 -->
<collection property="students" javaType="ArrayList" ofType="Student">
<result property="id" column="sid"/> <!-- 学生的id -->
<result property="name" column="sname"/> <!-- 学生的名字 -->
<result property="tid" column="tid"/> <!-- 对应的老师的id -->
</collection>
</resultMap>

这里的查询结果在分页计数的时候会有问题,
因为直接映射对象,查询的结果数量为映射对象的数量,在这里就是学生的数量
而分页需要的应该显示这一个老师信息,也就是一条信息
所以在一对多用到计数的时候,需要使用子查询映射

1
2
3
4
5
6
7
<!-- 子查询映射的方式-->
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!-- select查询学生的信息getStudent-->
<collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudent"/>
</resultMap>

多对一

实体类创建

因为从学生的角度来看,单个学生对应一个科目老师,所以老师实体类正常创建
学生的实体类中增加 private Teacher teacher;的对应关系

映射*Mapper.xml

学生的查询结果集<resultMap>中,增加<association>标签设置老师对应属性

1
2
3
4
5
6
7
<resultMap id="StudentToTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/> <!-- 老师名字 -->
</association>
</resultMap>

此处为结果映射,也可以使用子查询进行映射

1
2
<!-- column为在学生表中对应的老师id的列名 -->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>