表的员工与部门有对应关系,实体类之间也有对应的关系
在员工实体类中加入实体类部门属性
Dept dept;
查询员工信息以及员工所对应的部门信息
association专门处理多对一的映射关系
* property:表示需要处理的多对一关系的属性名
* javaType:表示该属性的类型
通过分步查询(常用):必须在核心配置文件中配置核心配置信息(将下划线映射为驼峰的那个)
* 好处:
* 可以实现延迟加载,在mybatis中默认是不加载的
核心配置信息:
分为两步
第一步:查询员工信息
select:设置分布查询的sql的唯一标识(namespacesqlID或mapper接口的全类名.方法名
column:设置分步查询的条件
property:处理的实体中的多对一的属性
第二步:查询部门信息
在部门实体类中加入员工类构成的集合
private List<Emp> emps;
collection:用来处理一对多的映射关系
property:处理一对多关系的属性
ofType:表示该属性对应的集合中存储的数据的类型
<resultMap id="deptAndEmpResultMap" type="Dept">
<id property="did" column="did"></id>
<result property="deptName" column="dept_name"></result>
<!--
collection:用来处理一对多的映射关系
property:处理一对多关系的属性
ofType:表示该属性对应的集合中存储的数据的类型
-->
<collection property="emps" ofType="Emp">
<id property="eid" column="eid"></id>
<result property="empName" column="emp_name"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
<result property="email" column="email"></result>
</collection>
</resultMap>
<!--Dept getDeptAndEmp(@Param("did") Integer did);-->
<select id="getDeptAndEmp" resultMap="deptAndEmpResultMap">
select * from t_dept left join t_emp on t_dept.did=t_emp.did where t_dept.did=#{did}
</select>
第一步:查询部门信息
<resultMap id="deptAndEmpByStepResultMap" type="Dept">
<id property="did" column="did"></id>
<result property="deptName" column="dept_name"></result>
<collection property="emps"
select="com.li.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
column="did">
</collection>
</resultMap>
<!-- Dept getDeptAndEmpByStepOne(@Param("did") Integer di);-->
<select id="getDeptAndEmpByStepOne" resultMap="deptAndEmpByStepResultMap">
select * from t_dept where did=#{did}
</select>
第二步:查询员工信息
<!-- List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did); -->
<select id="getDeptAndEmpByStepTwo" resultType="Emp">
select * from t_emp where did =#{did}
</select>