两张表
员工表(Employee): id last_name email gender
部门表(Dept) d_id(与上述id一样)dept_name
// 使用association进行分布查询
//public Employee getEmpByIdStep(Integer id);
<resultMap id="MyEmpByStep" type="com.atguigu.mybatis.dao/.Employee">
//1.先按照员工id查询员工信息
//2.根据查询员工信息中的d_id值去部门表中查出部门信息
//3.部门设置到员工中
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="email" property="email"/>
<result column="gender" property="gender"/>
<!-- association定义关联对象的封装规则(放另一张表)-->
<association property="dept"
select="com/atguigu/mybatis/dao/DepartmentMapper.getDeptById"
column="d_id">
</association>
</resultMap>
<select id="getEmpByIdStep" resultMap="MyEmpByStep">
select * feom tbl_employee where id=#{id}
</select>
延迟加载
Employee==>Dept (Employee中关联Dept)
我们每次查询Employee对象的时候,一起查出来,但是我们希望部门信息在我们使用时再进行查询,于是在分段查询的基础上,加上两个配置(在总配置文件中)
<settings>
//驼峰命名法开启
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 显示的指定我们需要更改的值-->
//延迟加载
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
两个表联合查询,其中有一个属性是集合时
与association类似,association属于定义单个对象级联,ollection定义集合类型属性的封装规则
<!-- public class Department{
private Integer id;
private String departmentName;
private List<Employee> emps; 这是一个集合属性
}
-->
正式代码:
<resultMap id="MyDept" type="com.atguigu.mybatis.bean.Department.java">
<id column="did" property="id"/>
<result column="dept_name" property="departmentName"/>
<result column="dept_name" property="departmentName"/>
<!-- collection定义集合类型属性的封装规则-->
<collection property="emps" ofType="com.atguigu.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>
<select id="getDeptByIdPlus" resultMap="MyDept">
select d.id,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 tbk_employee e
on d.id=e.d_id
where d.id=#{id}
</select>