自定义映射resultMap( 二 )

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

  • 分步查询的优点:可以实现延迟加载,但是必须在核心配置文件中设置全局配置信息:
    lazyLoadingEnabled:延迟加载的全局开关,当开启时,所有关联对象都会延迟加载 。
    aggressiveLazyLoading:当开启时,任何方法的调用都会加载该对象的所有属性 。否则,每个属性会按需加载
    此时就可以实现按需加载 , 获取的数据是什么 , 就会执行相应的sql 。此时可通过association和collection中的fetchType属性设置当前的分步查询是否使用延迟加载 。
  • 一对多的映射关系1.collection/*** 根据部门id查部门中员工的信息* @param deptId* @return*/Dept getDeptAndEmpByDeptId(@Param("deptId") Integer deptId);【自定义映射resultMap】<resultMap id="deptAndEmpResultMap" type="Dept"><id column="dept_id" property="deptId"></id><result column="dept_name" property="deptName"></result><!--ofType:设置collection标签所处理的集合属性中存储数据的类型--><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 getDeptAndEmpByDeptId(@Param("deptId") Integer deptId);--><select id="getDeptAndEmpByDeptId" resultMap="deptAndEmpResultMap">select *from t_deptLEFT JOIN t_empON t_dept.dept_id = t_emp.dept_idWHERE t_dept.dept_id = #{deptId};</select>2.分步查询
    • 查询部门信息
      /*** 分步查询部门以及部门中的员工信息第一步* @param id* @return*/Dept getDeptAndEmpByStepOne(@Param("id") Integer id);<resultMap id="deptAnEmpResultMapByStep" type="Dept"><id column="dept_id" property="depyId"></id><result column="dept_name" property="deptName"></result><collection property="emps"select="com.atguigu.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"column="dept_id"></collection></resultMap><!--Dept getDeptAndEmpByStepOne(@Param("id") Integer id);--><select id="getDeptAndEmpByStepOne" resultMap="">select * from t_dept where dept_id = #{deptId}</select>
    • 根据部门id查询部门中的员工信息
      /*** 分步查询部门以及部门中的员工信息第二步* @param dept_id* @return*/List<Emp> getDeptAndEmpByStepTwo(@Param("dept_id") Integer dept_id);<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><association property="dept"select="com.atguigu.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"column="dept_id"></association></resultMap><!--List<Emp> getDeptAndEmpByStepTwo(@Param("dept_id") Integer dept_id);--><select id="getDeptAndEmpByStepTwo" resultType="Emp">select * from t_emp where dept_id = #{deptId}</select>

    推荐阅读