处理一对多的映射关系

一对多关系,比如说根据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 天前
Spring Boot项目如何使用MyBatis实现分页查询
spring boot·后端·mybatis
一缕叶2 天前
mybatis(78/134)
mybatis
安清h2 天前
【基于SprintBoot+Mybatis+Mysql】电脑商城项目之用户注册
数据库·后端·mysql·spring·mybatis
yang_shengy3 天前
【JavaEE】Spring(5):Mybatis(上)
spring·java-ee·mybatis
字节全栈_PVK3 天前
Flask数据的增删改查(CRUD)_flask删除数据自动更新
数据库·flask·mybatis
花心蝴蝶.4 天前
MyBatis 入门
java·spring boot·后端·mybatis
or77iu_N4 天前
SpringBoot 中的测试jar包knife4j(实现效果非常简单)
java·开发语言·spring boot·后端·mybatis·jar
苏-言4 天前
SSM框架探秘:Spring 整合 Mybatis 框架
java·spring·mybatis
yang_shengy5 天前
【JavaEE】Spring(6):Mybatis(下)
spring·java-ee·mybatis