处理一对多的映射关系

一对多关系,比如说根据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>
相关推荐
丑八怪大丑6 小时前
MyBatis
mybatis
从此以后自律12 小时前
MyBatis 与 MyBatis-Plus 完整对比讲解
mybatis
SQL-First布道者15 小时前
Spring JDBC Ultra 十边型战士
java·spring boot·后端·mysql·spring·mybatis
han_hanker2 天前
sql语法 MyBatis <foreach> 标签详解
windows·sql·mybatis
ByWalker_3 天前
web应用技术—MyBatis入门
java·数据库·mybatis·lombok
ylscode3 天前
Cloudflare Workers Cache 深度解析:边缘缓存如何重塑无服务器性能边界
java·spring·mybatis
risc1234565 天前
Roaring Bitmap
java·开发语言·mybatis
Wang's Blog6 天前
JavaWeb快速入门: MyBatis入门与实战
java·mybatis
前端炒粉6 天前
马克思主义基本原理在MyBatis框架中的指导作用探析
mybatis·马克思主义
.Hypocritical.6 天前
MyBatis-Plus笔记
mybatis·mybatisplus