处理一对多的映射关系

一对多关系,比如说根据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>
相关推荐
小北方城市网5 小时前
MySQL 索引优化实战:从慢查询到高性能
数据库·spring boot·后端·mysql·rabbitmq·mybatis·java-rabbitmq
小北方城市网7 小时前
生产级 Spring Boot + MyBatis 核心配置模板
java·spring boot·redis·后端·spring·性能优化·mybatis
二等饼干~za8986689 小时前
Geo优化源码开发:关键技术解析与实践
数据库·sql·重构·mybatis·音视频
WZTTMoon10 小时前
MyBatis SQL执行流程详解
sql·mybatis
消失的旧时光-194310 小时前
第六课 · 6.1 从 JDBC 到 MyBatis:SQL 工程化是如何发生的?
java·sql·mybatis
熊出没11 小时前
关于MyBatis Mapper 接口与 XML 映射机制的分析
xml·microsoft·mybatis
小北方城市网12 小时前
MyBatis 进阶实战:插件开发与性能优化
数据库·redis·python·elasticsearch·缓存·性能优化·mybatis
panzer_maus1 天前
Redis简单介绍(3)-持久化的实现
java·redis·mybatis
Elieal1 天前
MybatisPlus难懂点
数据库·mybatis
迷路剑客1 天前
ES-7.10-高亮HighLight知识点总结
java·数据库·mybatis