处理一对多的映射关系

一对多关系,比如说根据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>
相关推荐
计算机学姐1 小时前
基于SpringBoot的校园二手书籍交易系统【个性化推荐+数据可视化统计+我买到的+我卖出的】
vue.js·spring boot·后端·mysql·信息可视化·intellij-idea·mybatis
zjneymar2 小时前
Mybatis的动态sql
java·sql·mybatis
稻草猫.3 小时前
MyBatis-Plus高效开发全攻略
java·数据库·后端·spring·java-ee·mybatis·mybatis-plus
计算机学姐4 小时前
基于SpringBoot的网吧管理系统
java·spring boot·后端·spring·tomcat·intellij-idea·mybatis
弹简特4 小时前
【JavaEE20-后端部分】 MyBatis 入门第四篇:多表查询、#{}与${}详解、数据库连接池
数据库·mybatis
哆啦A梦158813 小时前
Springboot整合MyBatis实现数据库操作
数据库·spring boot·mybatis
弹简特21 小时前
【JavaEE19-后端部分】 MyBatis 入门第三篇:使用XML完成增删改查
xml·mybatis
小江的记录本1 天前
【VO、DTO、Entity】VO、DTO、Entity三大核心数据对象全解析(附核心对比表 + 代码示例)
java·数据库·spring boot·spring·架构·mybatis·数据库架构
计算机学姐1 天前
基于SpringBoot的流浪动物救助收养系统
vue.js·spring boot·后端·mysql·java-ee·intellij-idea·mybatis
计算机学姐1 天前
基于SpringBoot的蛋糕烘焙销售服务系统
java·spring boot·后端·spring·tomcat·intellij-idea·mybatis