自定義映射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>

    推薦閱讀