处理一对多的映射关系

一对多关系,比如说根据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>
相关推荐
一只猿Hou6 小时前
java分页插件| MyBatis-Plus分页 vs PageHelper分页:全面对比与最佳实践
java·mybatis
java—大象10 天前
基于java SSM的房屋租赁系统设计和实现
java·开发语言·数据库·spring boot·layui·mybatis
Mutig_s10 天前
Spring Boot动态数据源切换:优雅实现多数据源管理
java·数据库·spring boot·后端·mybatis
编程乐学(Arfan开发工程师)10 天前
73、单元测试-断言机制
服务器·数据库·servlet·单元测试·sqlite·log4j·mybatis
小时候的阳光10 天前
MyBatis 的一级缓存导致的数据一致性问题分析
缓存·mybatis·事务·隔离级别
烙印60110 天前
MyBatis原理剖析(三)--加载配置文件
服务器·tomcat·mybatis
demon755200311 天前
Mybatis-Plus支持多种数据库
mybatis·多数据库
能工智人小辰11 天前
二刷苍穹外卖 day03
java·开发语言·mybatis
2401_8260976211 天前
JavaEE-Mybatis初阶
java·java-ee·mybatis