处理一对多的映射关系

一对多关系,比如说根据id查询一个部门的部门信息及部门下的员工信息

在Dept类中先添加List emps属性

1、collection

DeptMapper.xml文件中

xml 复制代码
<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>

2、分布查询

DeptMapper.xml文件中:

xml 复制代码
 <resultMap id="deptAndEmpByStepResultMap" type="Dept">
        <id property="did" column="did"></id>
        <result property="deptName" column="dept_name"></result>
        <collection property="emps"
                    select="com.atguigu.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
                    column="did"
                    fetchType="eager"></collection>
    </resultMap>
    <!--Dept getDeptAndEmpByStepOne(@Param("did") Integer did);-->
    <select id="getDeptAndEmpByStepOne" resultMap="deptAndEmpByStepResultMap">
        select * from t_dept where did=#{did}
    </select>

EmpMapper.xml文件中:

xml 复制代码
 <!--List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);-->
    <select id="getDeptAndEmpByStepTwo" resultType="Emp">
        select * from t_emp where did=#{did}
    </select>
相关推荐
Mcband1 天前
MyBatis 拦截器让搞定监控、脱敏和权限控制
mybatis
╭╰4021 天前
苍穹外卖优化-续
java·spring·mybatis
weixin_456904271 天前
基于Spring Boot + MyBatis的用户管理系统配置
spring boot·后端·mybatis
码熔burning2 天前
Redis 的三种高效缓存读写策略!
redis·缓存·mybatis
stein_java2 天前
Mybatis-7 XML映射器
数据库·sql·mybatis
托比-马奎尔2 天前
MyBatis入门到精通:CRUD实战指南
mybatis
ByteBlossom2 天前
MyBatis高频问题-自动映射与缓存解析
mybatis
半夏陌离2 天前
SQL 进阶指南:视图的创建与使用(视图语法 / 作用 / 权限控制)
java·数据库·mybatis
BillKu3 天前
Spring Boot中MyBatis的定义与使用
spring boot·mybatis
lozhyf3 天前
固定资产管理系统(vue+Springboot+mybatis)
vue.js·spring boot·mybatis