处理一对多的映射关系

一对多关系,比如说根据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>
相关推荐
qqty12171 小时前
springboot+mybaties项目中扫描不到@mapper注解的解决方法
java·spring boot·mybatis
灵魂猎手1 小时前
14. MyBatis XML 热更新实战:告别重启烦恼
java·mybatis
两年半的个人练习生^_^10 小时前
dynamic-datasource多数据源使用和源码讲解
java·开发语言·数据库·mybatis
weixin_7042660520 小时前
SpringBoot全注解开发指南
java·spring boot·mybatis
bug攻城狮1 天前
四大MyBatis增强框架深度对比与选型指南
架构·mybatis·数据库架构
それども1 天前
Mybatis xml 执行提示 NoSuchPropertyException
xml·mybatis
qq_366086221 天前
MyBatis 动态 SQL 高频性能优化方案
sql·性能优化·mybatis
aygh1 天前
互联网大厂Java面试场景:技术问答实录
mybatis·springboot·多线程·hashmap·java面试·arraylist·技术总结
独断万古他化1 天前
【Java 实战项目】多用户网页版聊天室:项目总览与用户 & 好友管理模块实现
java·spring boot·后端·websocket·mybatis
tsyjjOvO1 天前
SpringBoot 整合 MyBatis
java·spring boot·mybatis