接上篇mybatis使用associaton進行分步查詢html
相關的類仍是上篇中的類。sql
查詢部門的時候將部門對應的全部員工信息也查詢出來數據庫
DepartmentMapper.xml
mybatis
<!--嵌套結果集的方式,使用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.xml
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記錄封裝給Department
的emps
屬性。htm
注意:collection的分步查詢也是能夠延遲加載的,具體配置與上篇中的association
一致
另外,collection
元素中還有個fetchType
類型,也是用來控制延遲加載的,不過比全局配置的優先級更高。
fetchType
可選的。有效值爲 lazy
和eager
。 指定屬性後,將在映射中忽略全局配置參數lazyLoadingEnabled
,使用屬性的值。
補充:collection
中的column
屬性是數據庫中的列名,或着是列的別名,用來傳遞給select
屬性所指定語句中的參數,那若是須要傳遞多個參數該怎麼寫?
官方文檔: