Collection标签实现集合类的封装

本文介绍了MyBatis中Collection标签的使用方法,包括如何定义关联集合类型的属性封装规则及其实现分步查询的具体步骤。通过示例展示了如何查询部门及其所有员工的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Collection标签的使用和前面的association标签大同小易

主要是collection定义关联集合类型的属性的封装规则,而前面的association标签主要用来封装类,下面来看一下具体的用法:

假如现在要把部门中所有的员工查询出来,这时候就该轮到Collection登场了。

<select id="getDeptByIdPlus" resultMap="MyDept">
           SELECT d.id did,d.dept_name dept_name,e.id eid,
           e.last_name last_name,e.email email,e.gender gender
           from tb1_dept d left JOIN tb1_emplyee e on d.id=e.d_id where d.id=#{id}
 </select>
 <resultMap id="MyDept" type="com.test.beans.Department">
            <id column="did" property="id"/>
            <!--
               collection定义关联集合类型的
               属性的封装规则
               ofType:指定集合里边元素的类型
            -->
            <collection property="emps"
                        ofType="com.test.beans.Employee">
                <!--定义这个集合中元素的封装规则-->
                <id column="eid" property="id"/>
                <result column="last_name" property="lastName"/>
                <result column="email" property="email"/>
                <result column="gender" property="gender"/>
            </collection>
  </resultMap>
如果想要实现分步查询,步骤如下:

在emploeeMapper中定义如下的查询函数:

<select id="getEmpsByDeptId" resultType="com.test.beans.Employee">
        select * from tb1_emplyee where d_id=#{deptId}
    </select>

在部门的映射文件中编写如下的查询语句:

<select id="getDeptByIdStep" resultMap="MyDeptStep">
            SELECT  id,dept_name departmentName FROM  tb1_dept WHERE id=#{id}
        </select>
        <resultMap id="MyDeptStep" type="com.test.beans.Department">
            <id column="did" property="id"/>
            <id column="dept_name" property="departmentName"/>
            <collection property="emps"
                        select="com.test.dao.EmployeeMapperPlus.getEmpsByDeptId"
                        column="{deptId=id}" fetchType="lazy"></collection>
        </resultMap>

高亮处调用了前面定义的
getEmpsByDeptId
方法。

注:

多列的值传递过去:将多列的值封装map传递;
         column="{key1=column1,key2=column2}"
         fetchType="lazy":表示使用延迟加载;
            - lazy:延迟
            - eager:立即



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值