• 处理一对多映射关系的两种方式


     一对多关系实例:

    员工表:

     部门表:


    员工-部门关系表中,一个部门对应多个员工,想要在部门表中查询出对应的员工信息,就要解决一对多映射关系。

    解决方法:在Dept实体类中添加员工的LIst集合

    public class Dept {
        private Integer deptId;
        private String deptName;
    
        //处理一对多的关系
        private List emps;
    }

    有两种方式解决此问题

    1. Collection标签

    标签中映射Emp员工属性值

    property:关联的属性

    ofType:集合内部元素的类型(List就是Emp类型)

    1. Dept getDeptAndEmpByStepByCollection(@Param("deptId") Integer deptId);
    2. <resultMap id="getDeptAndEmpByStepByCollection" type="dept">
    3. <id column="dept_id" property="deptId">id>
    4. <result column="dept_name" property="deptName">result>
    5. <collection property="emps" ofType="emp">
    6. <id column="emp_id" property="empId">id>
    7. <result column="emp_name" property="empName">result>
    8. collection>
    9. resultMap>
    10. <select id="getDeptAndEmpByStepByCollection" resultMap="getDeptAndEmpByStepByCollection">
    11. SELECT * FROM t_dept left join t_emp on t_dept.dept_id = t_emp.dept_id WHERE t_dept.dept_id = #{deptId}
    12. select>

    2. 分步查询

    分别通过两个mapper查询各自的实体类属性,然后通过collection标签关联Emp.

    Empmapper

    1. List<Emp> getDeptAndEmpByStepTwo(@Param("deptId") Integer deptId);
    2. <select id = "getDeptAndEmpByStepTwo" resultType="emp">
    3. select * from t_emp where dept_id = #{dept_id}
    4. select>

    DeptMapper

    1. <resultMap id="getDeptAndEmpByStepOneResultMap" type="dept">
    2. <id column="dept_id" property="deptId">id>
    3. <result column="dept_name" property="deptName">result>
    4. <collection property="emps"
    5. select="com.zt.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
    6. column="dept_id">
    7. collection>
    8. resultMap>
    9. <select id="getDeptAndEmpByStepOne" resultMap="getDeptAndEmpByStepOneResultMap">
    10. select * from t_dept where dept_id = #{deptId}
    11. select>

    结果:
     

    1. Preparing: select * from t_dept where dept_id = ? (BaseJdbcLogger.java:137)
    2. Parameters: 2(Integer) (BaseJdbcLogger.java:137)
    3. Total: 1 (BaseJdbcLogger.java:137)
    4. Preparing: select * from t_emp where dept_id = ? (BaseJdbcLogger.java:137)
    5. Parameters: 2(Integer) (BaseJdbcLogger.java:137)
    6. Total: 2 (BaseJdbcLogger.java:137)
    7. Dept(deptId=2, deptName=B, emps=[Emp(empId=2, empName=李四, age=34, gender=男, dept=null), Emp(empId=4, empName=张涛, age=24, gender=男, dept=null)])

  • 相关阅读:
    MindStudio模型训练场景精度比对全流程和结果分析
    在智能家居领域产品中常用芯片
    【定时开关机】windows 10 如何设置定时开关机
    leetcode/爬楼梯的最少成本
    Northwestern University-844计算机科学与技术/软件工程-复试注意事项【考研复习】
    用XML的方式装配Bean
    漫画:国内都有哪些程序员大牛?
    python爬虫小案例——汽车之家
    cnn训练自己数据集
    ES6 -- 模块化(CommonJS、AMD、ES Module)
  • 原文地址:https://blog.csdn.net/qq_41950447/article/details/127822825