MyBatis-一对多的映射关系(collection和分步查询)

通过id获取部门及员工信息

1. 使用 collection 方法

1)在部门表中添加员工集合(对于一对多来说:一方添加多方的对象,而多方添加一方的集合)

Dept.java

public class Dept {
    private Integer deptId;
    private String deptName;
    private List<Emp> emps;
}

2)设置映射

DeptMapper.xml

association:处理多对一的映射关系(处理实体类类型的属性)

collection:处理一对多的映射关系(处理集合类型的属性)

ofType:设置集合类型的属性中存储的数据的类型

<resultMap id="deptAndEmpResultMap" type="Dept">
    <id column="dept_id" property="deptId"></id>
    <result column="dept_name" property="deptName"></result>
    <!--
        ofType:设置集合类型的属性中存储的数据的类型
    -->
    <collection property="emps" ofType="Emp">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <result column="age" property="age"></result>
        <result column="gender" property="gender"></result>
    </collection>
</resultMap>

<!-- Dept getDeptAndEmpById(@Param("deptId") Integer deptId);-->
<select id="getDeptAndEmpById" resultMap="deptAndEmpResultMap">
    select * from t_dept
    LEFT JOIN t_emp
    on t_dept.dept_id = t_emp.dept_id
    where t_dept.dept_id=#{deptId}
</select>

3)测试

@Test
public void testGetDeptAndEmpByDeptId(){
    SqlSession sqlSession = SqlSessionUtil.getSqlSession();
    DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);
    Dept dept = mapper.getDeptAndEmpById(1);
    System.out.println("dept = " + dept);
}

2. 分布查询

1)通过分步查询查询部门以及部门中的员工信息的第一步

DeptMapper.java

    Dept getDeptAndEmpByStepOne(@Param("deptId") Integer deptId);

DeptMapper.xml

<!--Dept getDeptAndEmpByStepOne(@Param("deptId") Integer deptId);-->
    <select id="getDeptAndEmpByStepOne" resultMap="">
        select * from t_dept where dept_id = #{deptId}
    </select>

2)通过分步查询查询部门以及部门中的员工信息的第二步

EmpMapper.xml

    List<Emp> getDeptAndEmpByStepTwo(@Param("deptId") Integer deptId);

DeptMapper.xml

    <!--List<Emp> getDeptAndEmpByStepTwo(@Param("deptId") Integer deptId);-->
    <select id="getDeptAndEmpByStepTwo" resultType="Emp">
        select * from t_emp where dept_id = #{deptId}
    </select>

3)建立联系

    <resultMap id="deptAndEmpResultMapByStep" type="Dept">
        <id column="dept_id" property="deptId"></id>
        <result column="dept_name" property="deptName"></result>
        <collection property="emps"
                    select="com.atguigu.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
                    column="dept_id"></collection>
    </resultMap>

 

posted @   浑浑噩噩一只小迷七  阅读(222)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示