赞
踩
前言:
在数据库操作中,我们可能习惯了单表、连表操作,突然然你来进行一对多操作,你还会吗?
什么是一对多?
一对多是最基础的表关系,简单来说就是 A 表中的一条数据对应 B 表中的多条数据,常见场景如下:
collection 标签
Mybatis 提供了 collection 标签帮助我们简化了一对多关系的查询,collection 标签一般使用于 resultMap 标签中。
collection 属性:
案例
本文以部门和部门下人员作为演示案例,分别有部门表 dept_info 和人员表 employee_info,使用一对多查询部门下的人员。
方法一,联合查询 ResultMap 映射:
<resultMap id="treeMap" type="com.zt.dc.portal.admin.web.pojo.dto.bulletinboard.DepartmentPersonnelTreeVO">
<result property="deptName" column="dept_name"/>
<result property="deptId" column="dept_id"/>
<result property="parentId" column="parent_id"/>
<collection property="deptEmployee" ofType="com.zt.dc.portal.admin.web.pojo.entity.EmployeeInfo">
<result property="name" column="name"/>
<result property="jobNumber" column="job_number"/>
</collection>
</resultMap>
<select id="queryDepartmentPersonnel" resultMap="treeMap">
select di.dept_name ,di.dept_id ,di.parent_id ,ei.name ,ei.job_number
from dept_info di left join employee_info ei on di.dept_id =ei.dept_id and ei.emp_type = 1
where di.dept_type = 1
</select>
方法二,子查询映射:
<resultMap id="treeMap2" type="com.zt.dc.portal.admin.web.pojo.dto.bulletinboard.DepartmentPersonnelTreeVO">
<result property="deptName" column="dept_name"/>
<result property="deptId" column="dept_id"/>
<result property="parentId" column="parent_id"/>
<collection property="deptEmployee" select="queryEmployeeInfo" column="dept_id"/>
</resultMap>
<select id="queryDepartmentPersonnel" resultMap="treeMap2">
select di.dept_name ,di.dept_id ,di.parent_id
from dept_info di
</select>
<select id="queryEmployeeInfo" resultType="com.zt.dc.portal.admin.web.pojo.entity.EmployeeInfo">
select ei.name ,ei.job_number from employee_info ei where ei.dept_id=#{deptId}
</select>
使用推荐:
建议使用联合查询 ResultMap 映射的方式实现一对多,做了一个小小的测试,两种方式的效率对比,联合查询 ResultMap 映射的方式的效率远高于子查询映射的方式。
欢迎提出建议及对错误的地方指出纠正。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。