本文转载,参考https://blog.youkuaiyun.com/apple_5/article/details/72953946
有的时候我们在查询的时候会需要再一个对象里返回他的子对象里的一个list
场景:查询某个公司下,销售部和商务部下所有的人员
那么我们希望返回的数据结构是:
在mybatis里我们使用下面的方式,用一条sql语句查询出来
嵌套结果集方式
javaBean
public class Department {
private Integer id;
private String name;
private List<Employee> employees;}
接口
public Department getDepartmentByIdPlus(Integer id);
- 1
sql映射文件
<!--
private Integer id;
private String name;
private List<Employee> employees;
-->
<!-- 嵌套结果集的方式-->
<!--public Department getDepartmentByIdPlus(Integer id);-->
<resultMap id="myDept" type="com.stayreal.mybatis.Department">
<id column="did" property="id"/>
<result column="dept_name" property="name"/>
<!-- collection定义关联集合类型的属性封装规则
offType:指定集合中的元素类型
-->
<collection property="employees" ofType="com.stayreal.mybatis.Employee">
<id column="eid" property="id"/>
<result column="last_name" property="lastName"/>
<result column="email" property="email"/>
<result column="gender" property="gender"/>
</collection>
</resultMap>
<select id="getDepartmentByIdPlus" 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>