相關的類還是上篇中的類。
查詢部門的時候將部門對應的所有員工信息也查詢出來
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;
的屬性信息
DepartmentMapper.xml
:首先通過id="getDeptByIdStep"
的sql查出部門信息
再通過collection中的select="com.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"
調用EmployeeMapper.xml
中的查詢語句,column="id"
為傳遞的查詢條件的值,也就是將這個值賦給EmployeeMapper.xml
中的#{deptId}
<!-- 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
<!-- 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
屬性。
注意:collection的分步查詢也是可以延遲加載的,具體配置與上篇中的association
一致
另外,collection
元素中還有個fetchType
類型,也是用來控制延遲加載的,不過比全局配置的優先級更高。
fetchType
可選的。有效值為 lazy
和eager
。 指定屬性后,將在映射中忽略全局配置參數lazyLoadingEnabled
,使用屬性的值。
補充:collection
中的column
屬性是數據庫中的列名,或着是列的別名,用來傳遞給select
屬性所指定語句中的參數,那如果需要傳遞多個參數該怎么寫?
官方文檔: