resultMap关联查询封装结果集

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值