处理一对多的映射关系

一对多关系,比如说根据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>
相关推荐
就改了3 小时前
MyBatis核心类用法详解
java·spring boot·后端·mybatis
momo2 天前
Java+WebAI黑马知识点
java·spring boot·mybatis
snow@li2 天前
MyBatis:动态 SQL 全景梳理
数据库·sql·mybatis
就改了2 天前
Mybatis快速入门大全(详细版)
java·spring boot·mybatis
qq_171538852 天前
深入浅出 MyBatis XML:从入门到精通
xml·java·mybatis
万亿少女的梦1682 天前
基于SSM、JSP与MySQL的秦皇岛旅游服务管理系统设计与实现
mysql·mybatis·ssm·jsp·spring mvc
jaysee-sjc2 天前
【JavaWeb】JDBC与Mybatis零基础入门详解
java·开发语言·前端·mybatis
dear_bi_MyOnly3 天前
【MyBatis 操作数据库】
java·数据库·学习·mybatis·学习方法
用户3126874877203 天前
分页插件到底怎么拦截 SQL?MyBatis-Plus 插件机制原理一次讲透
mybatis
马优晨3 天前
pring Boot + MyBatis + Redis 项目分层架构详解 —— 各层职责、关系与工作流程
架构·mybatis·spring项目分层架构详解·spring项目架构详解·spring各层职责·spring关系与工作流程