#mybatis #mapper.xml 分步查询 与 级联查询 一对多案例

分步查询

<!-- 部门 Mapper XML 文件 -->

<!-- 查询某个部门及其下的所有员工,使用 resultMap 定义嵌套查询 -->
<select id="selectDepartmentWithEmployees" resultMap="DepartmentWithEmployeesResultMap">
    SELECT * FROM department WHERE department_id = #{departmentId}
</select>

<resultMap id="DepartmentWithEmployeesResultMap" type="Department">
    <!-- 部门的属性映射 -->
    <id property="departmentId" column="department_id"/>
    <result property="departmentName" column="department_name"/>

    <!-- 嵌套查询,查询该部门下的所有员工 -->
    <collection property="employees" ofType="Employee" column="department_id" select="selectEmployeesByDepartmentId"/>
</resultMap>
<!-- 员工 Mapper XML 文件 -->

<!-- 查询某个部门下的所有员工 -->
<select id="selectEmployeesByDepartmentId" resultType="Employee">
    SELECT * FROM employee WHERE department_id = #{departmentId}
</select>

级联查询

<!-- 部门 Mapper XML 文件 -->

<!-- 查询某个部门及其下的所有员工,使用级联查询 -->
<select id="selectDepartmentWithEmployees" resultMap="DepartmentWithEmployeesResultMap">
    SELECT d.*, e.* FROM department d
    LEFT JOIN employee e ON d.department_id = e.department_id
    WHERE d.department_id = #{departmentId}
</select>

<resultMap id="DepartmentWithEmployeesResultMap" type="Department">
    <id property="departmentId" column="department_id"/>
    <result property="departmentName" column="department_name"/>

    <!-- 嵌套结果集映射,将员工的属性映射到 employees 集合中 -->
    <collection property="employees" ofType="Employee">
        <id property="employeeId" column="employee_id"/>
        <result property="employeeName" column="employee_name"/>
        <!-- 其他员工的属性映射 -->
    </collection>
</resultMap>
  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值