一、级联查询
使用 SQL 语句将相关联的两张表对应内容查询出来,再封装到 POJO。
<!-- 级联查询 -->
<resultMap type="employee" id="MyMap">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="age" property="age"/>
<result column="dept_id" property="department.id"/>
<result column="dept_name" property="department.departmentName"/>
</resultMap>
<select id="getEmpAndDepart" resultMap="MyMap">
SELECT e.`id` id,e.`last_name` last_name,e.`age` age ,e.`email` email,
d.`id` dept_id,d.`dept_name` dept_name
FROM employee e,department d WHERE e.`dept_id` = d.`id`
AND e.id = #{id}
</select>
二、分段查询
分段查询,将查询操作分为几段步骤,比如要查询关联两张表的数据:
- 先通过查询条件在第一张表中获取到数据。
- 再带着外键去关联的表中查询。
association:
- 复杂对象映射
- POJO中的属性可能会是一个对象
- 我们可以使用联合查询,并以级联属性的方式封装对象。
<resultMap type="employee" id="MyMapStep">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="age" property="age"/>
<!--
对于级联属性:
1.select :去调用指定的方法查询
2.column :指定哪一个字段作为传入的参数
-->
<association property="department"
select="cn.edu.pzhu.cg.dao.DepartmentMapper.getDeptById"
column="dept_id">
</association>
</resultMap>
<select id="getEmpByStep" resultMap="MyMapStep">
select * from employee where id=#{id}
</select>
当关联属性是一个集合时,在映射时需要使用到 collection 标签
<!-- 级联查询 -->
<resultMap type="cn.edu.pzhu.cg.entities.Department" id="MyDeptStep">
<id column="id" property="id"/>
<result column="departmentName" property="departmentName"/>
//映射集合属性
//emps 为 Department 的一个集合属性
<collection property="emps"
select="cn.edu.pzhu.cg.dao.EmployeeMapper.getEmps"
column="id">
</collection>
</resultMap>
<select id="getDeptAndEmpsById" resultMap="MyDeptStep">
select id id,dept_name departmentName from department where id=#{id}
</select>
三、延迟加载
在全局配置文件中添加配置:
<settings>
...
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
...
</settings>