ResultMap
使用场景:当mapper的映射文件中,实体类的名字与数据库字段名字不对应或者当其中包含这嵌套类的应用类型,实现一对一,一对多,多对多的情况.
一对一
一对多
<resultMap type="order" id="orderUserResultMap">
<!--type:类型
id :引用的名称id-->
<id property="id" column="id" />
<!-- property:实体类(POJO类)中字段属性名
column:数据库中对应字段-->
<result property="userId" column="user_id" />
<result property="number" column="number" />
<result property="createtime" column="createtime" />
<result property="note" column="note" />
<!-- association :配置一对多属性 -->
<!-- property:order里面的User属性名 -->
<!-- javaType:属性类型 -->
<association property="user" javaType="user">
<!-- id:声明主键,表示user_id是关联查询对象的唯一标识-->
<id property="id" column="user_id"/>
<result property="username" column="username"/>
<result property="address" column="address"/>
</association>
</resultMap>
<!-- 一对多关联,查询订单,订单内部包含用户属性 -->
<select id="queryOrderUserResultMap" resultMap="orderUserResultMap">
SELECT
oreder.id,
oreder.user_id,
oreder.number,
oreder.createtime,
oreder.note,
u.username,
u.address
FROM
`order` o
LEFT JOIN `user` u ON oreder.user_id = u.id
</select>
嵌套查询(分布查询)
<!--嵌套查询(分步查询)多对一-->
<resultMap id="QueryEmp_Map3" type="Emp">
<id column="e_id"property="id"></id>
<result column="user_name" property="username"></result>
<!-- 一-->
<association property="dept"column="dept_id"select="com.zzx.mapper.DeptMapper.SelectDept"></association>
</resultMap>
<select id="QueryEmp3" resultMap="QueryEmp_Map3">
select * from emp where id=#{id}
</select>
<select id="selectDept" resultType="dept">
SELECT* FROM dept where id=#{id}
</select>
多对多
多对多的关联关系查询,同样可以使用前面介绍的元素进行处理(其用法和一对多关联关系查询语句用法基本相同)