处理一对多的映射关系

一对多关系,比如说根据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>
相关推荐
weixin_4250230019 小时前
Spring Boot + MyBatis Plus JOIN 分页多表查询项目文档
spring boot·后端·mybatis
undsky1 天前
【RuoYi-Eggjs】:多数据库与 MyBatis 特性详解
node.js·mybatis·egg.js
柒.梧.1 天前
MyBatis注解开发全解析:从基础CRUD到关联查询与延迟加载
mybatis
程序员侠客行1 天前
Mybatis入门到精通 一
java·架构·mybatis
又是忙碌的一天1 天前
Myvatis 动态查询及关联查询
java·数据库·mybatis
柒.梧.1 天前
深度解析MyBatis缓存机制:从基础原理到实战配置
缓存·mybatis
一直都在5721 天前
MyBatis缓存
缓存·mybatis
7澄11 天前
MyBatis缓存详解:一级缓存、二级缓存与实战优化
缓存·mybatis·一级缓存
胡闹541 天前
MyBatis-Plus 更新字段为 null 为何失效?
java·数据库·mybatis
侠客行03171 天前
Mybatis入门到精通 二
java·mybatis·源码阅读