Mybatis自定义映射resultMap——多对一映射处理

导读:本篇文章讲解 Mybatis自定义映射resultMap——多对一映射处理,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

查询员工信息以及员工所对应的部门信息
mybatis使用resultMap解决多对一映射处理时有三种方法,首先需要在实体类员工中设置部门属性。

1、级联方式处理映射关系

<resultMap id="empDeptMap" type="Emp"> 
	<id column="eid" property="eid"></id> 
	<result column="ename" property="ename"></result> 		
	<result column="age" property="age"></result> 
	<result column="sex" property="sex"></result> 					
	<result column="did" property="dept.did"></result> 
	<result column="dname" property="dept.dname"></result>
</resultMap> 

<!--Emp getEmpAndDeptByEid(@Param("eid") int eid);--> 
<select id="getEmpAndDeptByEid" resultMap="empDeptMap"> 
	select emp.*,dept.* from t_emp emp left join t_dept dept on emp.did = dept.did where emp.eid = #{eid} 
	</select>

2、使用association处理映射关系

<resultMap id="empDeptMap" type="Emp"> <id column="eid" property="eid"></id> <result column="ename" property="ename"></result> <result column="age" property="age"></result> <result column="sex" property="sex"></result> <association property="dept" javaType="Dept"> <id column="did" property="did"></id> <result column="dname" property="dname"></result> </association> </resultMap> <!--Emp getEmpAndDeptByEid(@Param("eid") int eid);--> <select id="getEmpAndDeptByEid" resultMap="empDeptMap"> select emp.*,dept.* from t_emp emp left join t_dept dept on emp.did = dept.did where emp.eid = #{eid} </select>

3、分步查询

1)查询员工信息

/*** 通过分步查询查询员工信息 * @param eid * @return */ Emp getEmpByStep(@Param("eid") int eid);
<resultMap id="empDeptStepMap" type="Emp"> 
	<id column="eid" property="eid"></id> 
	<result column="ename" property="ename"></result> 
	<result column="age" property="age"></result> 
	<result column="sex" property="sex"></result> 
	<!--select:设置分步查询,查询某个属性的值的sql的标识(namespace.sqlId) column:将sql以及查询结果中的某个字段设置为分步查询的条件 -->
	<association property="dept" select="com.atguigu.MyBatis.mapper.DeptMapper.getEmpDeptByStep" column="did"> </association> 
</resultMap> 
<!--Emp getEmpByStep(@Param("eid") int eid);--> <select id="getEmpByStep" resultMap="empDeptStepMap">
	select * from t_emp where eid = #{eid} 
</select>

2)根据员工所对应的部门id查询部门信息

/** 
* 分步查询的第二步:根据员工所对应的did查询部门信息 
** @param did 
* @return 
* */
Dept getEmpDeptByStep(@Param("did") int did);
<!--Dept getEmpDeptByStep(@Param("did") int did);--> 

<select id="getEmpDeptByStep" resultType="Dept"> 
	select * from t_dept where did = #{did} 
</select>

**

个人建议使用分步查询,因为我们可以不用进行多个查询操作,不需要再重新写查询语句。

分步查询的优点:可以实现延迟加载,但是必须在核心配置文件中设置全局配置信息:
lazyLoadingEnabled:延迟加载的全局开关。当开启时,所有关联对象都会延迟加载
aggressiveLazyLoading:当开启时,任何方法的调用都会加载该对象的所有属性。 否则,每个
属性会按需加载
此时就可以实现按需加载,获取的数据是什么,就只会执行相应的sql。此时可通过association和
collection中的fetchType属性设置当前的分步查询是否使用延迟加载,fetchType=“lazy(延迟加
载)|eager(立即加载)”

**

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/63354.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!