resultMap关联查询封装结果集
一般业务中表与表(类与类)之间都有某种关联关系,即在查询这种关联信息时需要某种机制进行处理,使得查询结果更完善。
常用的标签:
- <association>关联一对一</association>
association – 复杂类型联合; 许多查询结果合成这个类型
一对一结果映射– associations 能引用自身, 或者从其它地方引用
- <collection>关联一对多</collection>
collection – 复杂类型集合
嵌套结果映射– collections 能引用自身, 或者从其它地方引用
一对一查询
- 一个员工对应一个部门
<!-- 手动返回值 -->
<resultMap type="User" id="userDept">
<!– 用 id 属性来映射主键字段 –>
<id property="id" column="userId"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
<result property="oper" column="oper"/>
<!-- property表示在java实体中属性的名称,javaType表示属性的类型 -->
<association property="dept" javaType="Dept">
<id property="id" column="deptId"/>
<result property="deptName" column="dept_name"/>
<result property="deptDesc" column="dept_desc"/>
</association>
</resultMap>
<select id="findUserDept" parameterType="int" resultMap="userDept">
SELECT tu.id userId,tu.name,tu.sex,tu.age,
tu.oper,td.id deptId,td.dept_name,td.dept_desc
FROM t_user tu
LEFT JOIN t_dept td ON tu.dept_id = td.id
WHERE tu.id = #{id}
</select>
一对多查询
- 一个部门对应多个员工
<!-- 手动返回值 -->
<resultMap type="Dept" id="deptMap">
<!– 用 id 属性来映射主键字段 –>
<id property="id" column="deptId"/>
<!–用 result 属性来映射非主键字段,property 为实体类属性名,column为数据表中的属性–>
<result property="deptName" column="dept_name"/>
<result property="deptDesc" column="dept_desc"/>
<!-- property表示java实体中的属性名,ofType表示集合的泛型 -->
<collection property="userlist" ofType="User">
<id property="id" column="userId"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
</collection>
</resultMap>
<!– 查询语句
id:唯一标识该语句,对应于dao层的抽象方法;
paramterType:参数的类型
resultMap:对应的resultMap标签的id值,封装结果集
–>
<select id="findDpetById" parameterType="int" resultMap="deptMap">
SELECT tu.id userId,tu.name,tu.sex,tu.age,
td.id deptId,td.dept_name,td.dept_desc
FROM t_dept td
LEFT JOIN t_user tu ON tu.dept_id = td.id
WHERE td.id = #{id}
</select>