相关的类还是上篇中的类.
第一种查询部门的时候将部门对应的所有员工信息也查询出来的方式:
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 记录封装给 Department 的 emps 属性.
注意: collection 的分步查询也是可以延迟加载的, 具体配置与上篇中的 association 一致
另外, collection 元素中还有个 fetchType 类型, 也是用来控制延迟加载的, 不过比全局配置的优先级更高.
fetchType | 可选的。有效值为 & nbsp;lazy 和 & nbsp;eager。 指定属性后,将在映射中忽略全局配置参数 & nbsp;lazyLoadingEnabled,使用属性的值。 |
---|---|
补充: collection 中的 column 属性是数据库中的列名, 或着是列的别名, 用来传递给 select 属性所指定语句中的参数, 那如果需要传递多个参数该怎么写?
官方文档:
- ASPCode
- CreateFolder
- DeleteFolder
- ShortName
- SubFolders
- Files
- ParentFolder
- DateCreated
来源: http://www.bubuko.com/infodetail-3462457.html