接上篇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
属性所指定语句中的参数,那若是须要传递多个参数该怎么写?
官方文档: