mybatis使用collection查詢集合屬性規則

接上篇mybatis使用associaton進行分步查詢html

相關的類仍是上篇中的類。sql

查詢部門的時候將部門對應的全部員工信息也查詢出來數據庫

DepartmentMapper.xmlmybatis

<!--嵌套結果集的方式,使用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分步查詢app

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

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

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

<!-- collection:分步查詢 -->
    <resultMap type="com.mybatis.bean.Department" id="MyDeptStep">
        <id column="id" property="id"/>
        <id column="dept_name" property="departmentName"/>
        <collection property="emps" 
            select="com.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"
            column="id"></collection>
    </resultMap>
    <!-- public Department getDeptByIdStep(Integer id); -->
    <select id="getDeptByIdStep" resultMap="MyDeptStep">
        select id,dept_name from tbl_dept where id=#{id}
    </select>

EmployeeMapper.xmlxml

<!-- 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屬性。htm

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


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

fetchType 可選的。有效值爲 lazyeager。 指定屬性後,將在映射中忽略全局配置參數 lazyLoadingEnabled,使用屬性的值。

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

官方文檔:

相關文章
相關標籤/搜索