Collection标签实现集合类的封装

来源:互联网 发布:网管软件破解版 编辑:程序博客网 时间:2024/06/04 23:25

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:立即



原创粉丝点击