ResultMap梳理
- ResultMap概述
Mybatis当中最强大的映射元素。实际上是用来进行javaBean和表记录的自定义映射的。另外由于MyBatis提供了非常强大的jdbcType和javaType之间的类型转换机制,所以在映射的时候,关于类型不需要我们做太多的处理
- 关于ResultMap和ResultType的关系
ResultMap 自定义映射,处理复杂的结果映射(尤其是嵌套关系的类型)
ResultType 自动映射,处理简单类型的结果映射
但是,本质上,ResultType就是使用ResultMap机制。
当我们使用ResultType的时候,MyBatis会自动创建一个空的ResultMap进行映射。
- ResultMap的基本使用
- 使用公有的getter/setter方式,将记录当中的字段值映射到JavaBean的属性当中
<ResultMap id=”” type=””>
<id column=”表列名” property=”javaBean属性名” /> <!-- 针对的是主键 ->
<result column=”表列名” property=”javaBean属性名”/> <!-- 针对的是普通的字段 ->
</ResultMap>
说明: ResultMap的id属性确定了 调用 这个ResultMap的名字,当我们配置了这么一个ResultMap,Mybatis容器读取到该映射文件的时候,会创建一个ResultMap的集合,此时,我们的查询<select> </select>指定了resultMap的id时,就会去ResultMap集合当中找到对应的ResultMap,从而进行结果映射
- 使用构造器的方式,进行结果映射
<resultMap type=" " id=" ">
<constructor>
<idArg column=" " name=" " />
<arg column=" " name=" " />
</constructor>
</resultMap>
调用的是构造器,那么我们需要创建对应的参数列表的构造器
在构造器的参数列表当中,通过@Param(“name”)指定name属性名称
- ResultMap实际应用——映射关系
- 使用到的元素:
“有一个“的关系:<association>
“有多个”的关系<collection>
- 映射关系:
一对一: <association>
多对一:<association>
一对多:<collection>
多对多:<collection>
- association的使用
- join连接(嵌套在内部、在外部引用)
select sid,s_num,s_name,s_gender,s_age,detail_id,stu_addr,stu_tel
from student s inner join
student_detail sd
on s.sid = sd.stu_id
where s.s_name = #{stuName};
- 内部
<resultMap id=”” type=”Student”>
````其余属性`````
<association property="detail” type="Detail">
<id column=" " property=" "></id>
<result column=" " property=" " />
</association>
</resultMap>
- 外部
<resultMap id=”detailMap” type=”Detail”>
<id></id>
<result></result>
</resultMap>
<resultMap id=”StudentMap” type = “Student”>
````````
<association property="detail" column="sid" javaType="Detail" resultMap="detailMap" />
</resultMap>
- 子查询(性能问题:N+1)
主查询:StudentMapper.xml
Select * from student whre s_name=#{stuName};
子查询:DetailMapper.xml
select * from student_detail where stu_id = #{stuId};
过程:
通过主查询拿到指定学生姓名的多条学生记录(假设有N条)(一次查询)
, 每条记录都拿外键,也就是学号,到子查询当中去查询详情记录(子查询执行N次)
<association property="detail" javaType="Detail" column="sid" select="com.nlg.mapper.DetailMapper.queryDetailByStuId" />