MyBatis中处理多对一的映射关系

1.级联方式处理
关键:明白字段应该映射哪一个属性

也就是将主表中主键为id,关联表中的要查询的值通过column对应数据库中名字,property对应实体类中的名字进行映射

<resultMap id="empAndDeptResultMapOne" type="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>
        <result column="dept_id" property="dept.deptId"></result>
        <result column="dept_name" property="dept.deptName"></result>
    </resultMap>

2.association标签
模板

 <resultMap id="empAndDeptResultMap" type="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>
        <!--
            association:处理多对一的映射关系(处理实体类类型的属性)
            property:设置需要处理映射关系的属性的属性名
            javaType:设置需要处理的属性的类型
        -->
        <association property="dept" javaType="Dept">
            <id column="dept_id" property="deptId"></id>
            <result column="dept_name" property="deptName"></result>
        </association>
    </resultMap>



3.分步查询

先查询出一个表中的数据

再利用该表中数据的某个元素在第二个表中查询数据

(注意,一般该方法的两个步骤写在在不同的接口中

因为他们对应的是不同的实体类,返回值不同)


优点:可以实现延迟加载,减少当前内存的消耗

 <resultMap id="empAndDeptByStepResultMap" type="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>
        <!--
            property:设置需要处理映射关系的属性的属性名
            select:设置分布查询的sql的唯一标识
            (在对应接口中找到对应方法通过右键选copy Reference复制
            或按ctrl+shift+alt+C复制)
            column:将查询处的某个字段作为分布查询的sql的条件
            fetchType:在开启了延迟加载的环境中,通过该属性
            来实现需要延迟加载还是立即加载(全部加载)
            fetchType:eager(立即加载,全部加载)/lazy(延迟加载)
        -->
        <association property="dept" fetchType="eager"
                     select="com.javasm.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
                     column="dept_id"></association>
posted @   别亦难  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示