Mybatis处理映射关系一对多的两种方式

文章介绍了在MyBatis中处理一对多关系的两种策略。第一种是使用`collection`标签在同一个SQL查询中获取部门及其所有员工。第二种是分步查询,先获取部门信息,再通过部门ID单独查询员工列表。这两种方法分别通过`resultMap`详细配置了映射规则。
摘要由CSDN通过智能技术生成

 例如:查询某部门基础信息及该部门下的所有员工

实体类---部门---Dept

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dept {
    private Integer deptId;
    private String  deptName;
    private List<Emp> emps;
}

EmpMapper.xml

    <select id="queryEmpByDeptId" resultType="Emp">
        select * from EMP where dept_id = #{deptId}
    </select>

具体处理一对多关系的两种方式:

  1、collection

<resultMap id="deptAndEmpMap" type="Dept">
    <id column="dept_id" property="deptId"></id>
    <result column="dept_name" property="deptName"/>
    <collection property="emps" ofType="Emp">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"/>
    </collection>
</resultMap>

 <select id="queryDeptAndEmp" resultMap="deptAndEmpMap">
     select  D.dept_id,
             D.dept_name,
             E.emp_id,
             E.emp_name
     from DEPT D LEFT JOIN EMP E ON D.dept_id = E.dept_id
     where D.dept_id = ${deptId}
 </select>

 2、分步查询

<resultMap id="deptAndEmpStepMap" type="Dept">
    <id column="dept_id" property="deptId"></id>
    <result column="dept_name" property="deptName"/>
    <collection property="emps" select="com.neusoft.mybatis.parameter.mapper.EmpMapper.queryEmpByDeptId" column="dept_id">
        <id column="emp_id" property="empId"/>
        <result column="emp_name" property="empName"/>
    </collection>
</resultMap>

<select id="queryDeptAndEmpByStep"  resultMap="deptAndEmpStepMap">
    select  * from  DEPT  where  dept_id = #{deptId}
</select>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流星雨洒满天空

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值