处理一对多的映射关系

一对多关系,比如说根据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>
相关推荐
菜鸟蹦迪34 分钟前
学习记录:mybatis和jdbc实现数据表作为参数的相关的sql操作
sql·学习·mybatis
芯眼1 天前
STM32启动文件详解(重点)
java·开发语言·c++·stm32·单片机·mybatis
遗憾皆是温柔1 天前
MyBatis—动态 SQL
java·数据库·ide·sql·mybatis
CircleMouse2 天前
springboot如何通过提供的注解方式来操作Redis
java·spring boot·redis·spring·mybatis
荔枝吻2 天前
【抽丝剥茧知识讲解】引入mybtis-plus后,mapper实现方式
java·sql·mybatis
Allen Bright3 天前
【MyBatis-9】MyBatis分页插件PageHelper深度解析与实践指南
mybatis
柴薪之王、睥睨众生4 天前
(自用)Java学习-5.8(总结,springboot)
java·开发语言·spring boot·学习·mybatis
唐僧洗头爱飘柔95274 天前
【SSM-SSM整合】将Spring、SpringMVC、Mybatis三者进行整合;本文阐述了几个核心原理知识点,附带对应的源码以及描述解析
java·spring·mybatis·springmvc·动态代理·ioc容器·视图控制器
意倾城4 天前
浅说MyBatis-Plus 的 saveBatch 方法
java·mybatis
Brilliant Nemo4 天前
五、框架实战:SSM整合原理和实战
maven·mybatis