Mybatis中处理一对多的映射关系

一对多与多对一的区别:

        以部门表为单位,一个部门会有很多员工为一对多的关系

以员工表为单位,会有多个员工在一个部门中为多对一的关系

一:collection

由于一个部门中会有多个员工,即一对多的关系因此我们需要的实体类Dept中存在一个集合属性,里面存放的数据类型为员工类型来存储多个员工

在resultMap中的映射关系为:

<resultMap id="deptAndEmpResultMap" type="Dept">
        <id property="did" column="did"></id>
        <result property="deptName" column="dept_name"></result>
        <!--
        collection 用来处理一对多的映射关系
        ofType:表示该属性对应的集合中的存储数据的类型
        -->
        <collection property="emps" ofType="Emp">
            <id property="eid" column="eid"></id>
            <result property="empName" column="emp_name"></result>
            <result property="age" column="age"></result>
            <result property="sex" column="sex"></result>
            <result property="email" column="email"></result>
        </collection>
    </resultMap>
    <!--Dept getDeptAndEmp(@Param("did") Integer did);-->
    <select id="getDeptAndEmp" resultMap="deptAndEmpResultMap">
        select * from t_dept left join t_emp on t_dept.did = t_emp.did where t_dept.did = #{did}
    </select>

这里使用了ofType,与之前多对一查询中不同的是ofType表示这个集合中存放的数据类型

 中javaType表示多对一关系中的属性类型。两个场景不同的方法罢了

二、分步查询

        第一步:查询部门信息

 <!--Dept getDeptAndEmpByStepOne(@Param("did") Integer did);-->
    <select id="getDeptAndEmpByStepOne" resultMap="deptAndEmpByStepOne">
        select * from t_dept where did = #{did}
    </select>

通过查询到的部门信息中的did,来在员工表中查找对应的员工信息

因此,在resultMap中

 <resultMap id="deptAndEmpByStepOne" type="Dept">
        <id property="did" column="did"></id>
        <result property="deptName" column="dept_name"></result>
        <collection property="emps"
                    select="mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
                    column="did">
        </collection>
    </resultMap>

需要指定第二步的sql语句的唯一标识以及查询的条件column did

 <!--List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);-->
    <select id="getDeptAndEmpByStepTwo" resultType="Emp">
        select * from t_emp where did = #{did}
    </select>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值