功能

表示该属性为“一”的一方

如教室与学生关系中的教室

使用

已知t_class(id,name)t_student(id,name,cid),外键为t_student.cid=t_class.id

设置实体clazz: Class(Integer id, String name)student: Student(Integer id, String name, Clazz clazz)

1
2
3
4
5
6
7
8
<resultMap id="resultClass" type="Clazz">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
</resultMap>
<resultMap id="resultStudent" type="Student">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
</resultMap>

公用属性

属性 功能 举例 说明
property 对应的实体列 student.clazz
column 外键列 t_student.cid 使用select时必选
将作为参数传入select
javaType 内嵌的实体类型 Clazz 不可与resultMap同时使用
可省略
jdbcType 外键列的类型 cid的类型
typeHandler 指定类型转换器 不常用
columnPrefix resultMap中column的前缀 “t_student_id”作为别名时,前缀为t_student_ 避免列名重复时会设置列名前缀区分

连接多表

属性 功能 举例 说明
resultMap 内嵌的实体类型的映射关系
用于引用其他resultMap
不可与javaType同时使用

association内部编写映射关系,或通过resultMap属性引入映射关系

为了对重复的列名加以区分设置了别名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<select id="selectWithClazz" resultMap="resultWithClazz">
select t.id as id, t.name as name, c.id = cid, c.name as cname
from t_student t join t_class c on t.cid=c.id
where id={#id}
</select>

<resultMap id="resultWithClazz" type="Student">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<association property="clazz" javaType="Clazz">
<id column="id" property="cid"/>
<result column="name" property="cname"/>
</association>
</resultMap>

或者将association的映射写入其他resultMap,因为选出的列名比resultClass中指定的column多一个前缀”c“,则需指定columnPrefix

1
<association property="clazz" resultMap="resultClass" columnPrefix="c"/>

引用外部SQL

属性 功能 举例 说明
select 引用其他SQL语句
该SQL语句需以column为参数,返回的类型必须与javaType相同
必须指定column
column 外键列,将会作为参数传入select指定的SQL语句 t_student.cid 使用select时必须指定column

使association通过指定columnselect填充嵌入的实体

association会将column作为参数传入selectselect将返回Clazz实体写入property

1
2
3
4
5
6
7
8
9
10
<select parameterType="int" id="selectClass" resultMap="resultClazz">
select id, name from user where id=#{id}
</select>
<select parameterType="int" id="selectStudent" resultMap="resultWithClazz">
select id, name, cid from student where id = #{id}
</select>

<resultMap id="resultWithClazz" type="Student" extends="resultStudent">
<association property="clazz" column="cid" javaType="Class" select="selectClass"/>
</resultMap>