resultMap自定義映射(一對多)


collection:處理一對多和多對多的關系
  1) POJO中的屬性可能會是一個集合對象,我們可以使用聯合查詢,並以級聯屬性的方式封裝對象.使用collection標簽定義對象的封裝規則

 

public class Dept {
    private Integer did;
    private String dname;
    private List<Emp> emps;
    // 省略 get/set方法
}
public class Emp {
    private Integer eid;
    private String ename;
    private Integer age;
    private String sex;
    private Dept dept;
    // 省略 get/set方法
}

查詢某一部門下的所有員工信息:

    <resultMap type="Dept" id="deptMap">
        <id column="did" property="did"/>
        <result column="dname" property="dname"/>
        <!-- 
            <collection>:處理一對多和多對多的關系
           ofType:指集合中的類型,不需要指定javaType -->
        <collection property="emps" ofType="Emp">
            <id column="eid" property="eid"/>
            <result column="ename" property="ename"/>
            <result column="age" property="age"/>
            <result column="sex" property="sex"/>
        </collection>
    </resultMap>
    
    <!-- Dept getDeptEmpsByDid(String did); -->
    <select id="getDeptEmpsByDid" resultMap="deptMap">
        select d.did,d.dname,e.eid,e.ename,e.age,e.sex from dept d left join emp e on d.did = e.did where d.did = #{did}
    </select>

   2)collection 分步查詢
  實際的開發中,對於每個實體類都應該有具體的增刪改查方法,也就是DAO層, 因此對於查詢部門信息並且將對應的所有的員工信息也查詢出來的需求,就可以通過分步的方式完成查詢。
    ① 先通過部門的id查詢部門信息
    ② 再通過部門id作為員工的外鍵查詢對應的信息.

   
    <!-- List<Emp> getEmpListByDid(String did); -->
    <select id="getEmpListByDid" resultType="Emp">
        select eid,ename,age,sex from emp where did = #{did}
    </select>
    
    <resultMap type="Dept" id="deptMapStep">
        <id column="did" property="did"/>
        <result column="dname" property="dname"/>
        <collection property="emps" select="com.atguigu.mapper.EmpDeptMapper.getEmpListByDid" column="{did=did}" fetchType="eager"></collection>
    </resultMap>
    
    <!-- Dept getOnlyDeptByDid(String did); -->
    <select id="getOnlyDeptByDid" resultMap="deptMapStep">
        select did,dname from dept where did = #{did}
    </select>

 column="{did=did}中如果有多個參數,則以map鍵值對的方式,但要注意在后面的sql語句中要對應好鍵的名稱。

 

擴展: association 或 collection的 fetchType屬性
  1) 在<association> 和<collection>標簽中都可以設置fetchType,指定本次查詢是否要使用延遲加載。默認為 fetchType= ”lazy” ,如果本次的查詢不想使用延遲加載,則可設置為fetchType=”eager”.
  2) fetchType可以靈活的設置查詢是否需要使用延遲加載,而不需要因為某個查詢不想使用延遲加載將全局的延遲加載設置關閉.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM