MyBatis框架
4.7.2 association
- POJO中的属性可能会是一个对象,我们可以使用联合查询,并以级联属性的方式封装对象.使用association标签定义对象的封装规则
public class Department { private Integer id ; private String departmentName ; // 省略 get/set方法 } |
public class Employee { private Integer id ; private String lastName; private String email ; private String gender ; private Department dept ; // 省略 get/set方法 }
|
- 使用级联的方式:
<select id="getEmployeeAndDept" resultMap="myEmpAndDept" > SELECT e.id eid, e.last_name, e.email,e.gender ,d.id did, d.dept_name FROM tbl_employee e , tbl_dept d WHERE e.d_id = d.id AND e.id = #{id} </select>
<resultMap type="com.atguigu.mybatis.beans.Employee" id="myEmpAndDept"> <id column="eid" property="id"/> <result column="last_name" property="lastName"/> <result column="email" property="email"/> <result column="gender" property="gender"/> <!-- 级联的方式 --> <result column="did" property="dept.id"/> <result column="dept_name" property="dept.departmentName"/> </resultMap> |
- Association‘
<resultMap type="com.atguigu.mybatis.beans.Employee" id="myEmpAndDept"> <id column="eid" property="id"/> <result column="last_name" property="lastName"/> <result column="email" property="email"/> <result column="gender" property="gender"/> <association property="dept" javaType="com.atguigu.mybatis.beans.Department"> <id column="did" property="id"/> <result column="dept_name" property="departmentName"/> </association> </resultMap> |
4.7.3 association 分步查询
- 实际的开发中,对于每个实体类都应该有具体的增删改查方法,也就是DAO层, 因此
对于查询员工信息并且将对应的部门信息也查询出来的需求,就可以通过分步的方式
完成查询。
- 先通过员工的id查询员工信息
- 再通过查询出来的员工信息中的外键(部门id)查询对应的部门信息.
<select id="getEmployeeAndDeptStep" resultMap="myEmpAndDeptStep"> select id, last_name, email,gender,d_id from tbl_employee where id =#{id} </select>
<resultMap type="com.atguigu.mybatis.beans.Employee" id="myEmpAndDeptStep"> <id column="id" property="id" /> <result column="last_name" property="lastName"/> <result column="email" property="email"/> <result column="gender" property="gender"/> <association property="dept" select="com.atguigu.mybatis.dao.DepartmentMapper.getDeptById" column="d_id" fetchType="eager"> </association> </resultMap> |
4.7.4 association 分步查询使用延迟加载
- 在分步查询的基础上,可以使用延迟加载来提升查询的效率,只需要在全局的
Settings中进行如下的配置:
<!-- 开启延迟加载 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 设置加载的数据是按需还是全部 --> <setting name="aggressiveLazyLoading" value="false"/> |