0%

mybatis5关系映射

mybatis不仅可以映射表到类,还可以映射表和表之间的关系。
我们需要把表和表之间的关系转化为类和类之间的关系。

类和类之间的关系:

纵向关系:

继承(父类)、实现(接口)

横向关系:

依赖关系(方法)、关联关系(属性)

本文仅对于关联关系进行描述说明,其他的可以参考其他的教程。
你可以简单的举例理解:

1
2
3
4
5
class Boy{
private List<Car> cars;
}
class Car{
}

表示为一个人可以拥有多辆车,即一对多关系。
这样的手法可以把关系型数据库中表的三种关系分别表示出来:
一对一,一对多,多对多

mybatis关系映射:

mybatis的关系映射表现了ORM的思想,我们需要手动的把他们对应起来。
比如查询所有年级和对应所有的学生信息,SQL很容易想出来为:

1
2
SELECT * FROM grade LEFT JOIN student
ON grade.`gid`=student.gid

但是我们需要处理结果,我们需要一个类型去承载结果。
改造Grade实体类:

1
private List<Student> students;//省略get和set

持久化操作:

1
2
3
4
5
6
7
8
9
10
<resultMap id="resultMapGradeAndStudent" type="cn.k2502.project.entity.Grade">
<result column="gname" jdbcType="VARCHAR" property="gname" />
<result column="gid" property="gid" />
<collection property="students" javaType="list" ofType="Student" autoMapping="true" notNullColumn="xh"></collection>
</resultMap>

<select id="selectGradeAndStudent" resultMap="resultMapGradeAndStudent">
SELECT * FROM grade LEFT JOIN student
ON grade.`gid`=student.gid
</select>

返回值类型使用resultMap,我们自己映射一下就好了。
对于集合我们可以使用collection标签映射,对于单个类使用association标签映射。
collection:集合
association:联合
javaType:Java类型
ofType:泛型类型
autoMapping:自动映射(auto自动,Mapping映射)
notNullColumn:非空列