mybatis使用collection標簽配置某個對象中的List集合類型的屬性例子


相關的類還是上篇中的類。

第一種查詢部門的時候將部門對應的所有員工信息也查詢出來的方式:

DepartmentMapper.xml

 
<!--嵌套結果集的方式,使用collection標簽定義關聯的集合類型的屬性封裝規則  -->
    <resultMap type="com.mybatis.bean.Department" id="MyDept">
        <id column="did" property="id"/>
        <result column="dept_name" property="departmentName"/>
        <!-- 
            collection定義關聯集合類型的屬性的封裝規則 
            ofType:指定集合里面元素的類型
        -->
        <collection property="emps" ofType="com.mybatis.bean.Employee">
            <!-- 定義這個集合中元素的封裝規則 -->
            <id column="eid" property="id"/>
            <result column="last_name" property="lastName"/>
            <result column="email" property="email"/>
            <result column="gender" property="gender"/>
        </collection>
    </resultMap>
    <!-- public Department getDeptByIdPlus(Integer id); -->
    <select id="getDeptByIdPlus" resultMap="MyDept">
        SELECT d.id did,d.dept_name dept_name,
                e.id eid,e.last_name last_name,e.email email,e.gender gender
        FROM tbl_dept d
        LEFT JOIN tbl_employee e
        ON d.id=e.d_id
        WHERE d.id=#{id}
    </select>

 

collection分步查詢

先通過部門表的id查出部門信息,再通過員工表的部門id查出所有的員工信息,也就是Department中的private List<Employee> emps;的屬性信息

 

第二種在查詢Department的同時查詢出employee的方式:

DepartmentMapper.xml:首先通過id="getDeptByIdStep"的sql查出部門信息

再通過collection中的select="com.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"調用EmployeeMapper.xml中的查詢語句,column="id"為傳遞的查詢條件的值,也就是將這個值賦給EmployeeMapper.xml中的#{deptId}

 

EmployeeMapper.xml

 
    <!-- public List<Employee> getEmpsByDeptId(Integer deptId); -->
    <select id="getEmpsByDeptId" resultType="com.atguigu.mybatis.bean.Employee">
        select * from tbl_employee where d_id=#{deptId}
    </select>

  

最后呢,也就是將查詢到的員工信息,即多條Employee記錄封裝給Departmentemps屬性。

注意:collection的分步查詢也是可以延遲加載的,具體配置與上篇中的association一致


另外,collection元素中還有個fetchType類型,也是用來控制延遲加載的,不過比全局配置的優先級更高。

fetchType 可選的。有效值為 lazy 和 eager。 指定屬性后,將在映射中忽略全局配置參數 lazyLoadingEnabled,使用屬性的值。
   

補充:collection中的column屬性是數據庫中的列名,或着是列的別名,用來傳遞給select屬性所指定語句中的參數,那如果需要傳遞多個參數該怎么寫?

官方文檔:

 

 
參考原文:https://www.cnblogs.com/heliusKing/p/11173362.html
 
 


免責聲明!

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



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