当需要实现多表查询的时候,通常需要使用association标签来进行结果集的嵌套。
ex:
考虑如下情形:
员工表的d_id字段和部门表的id字段有一个外键映射关系,现在需要把对应id的员工以及部门全部查找出来。
<select id="getEmpAndDept" resultMap="complexEmp2">
SELECT e.id id,e.last_name last_name,e.email email,e.gender gender,e.d_id d_id,
d.id did,d.dept_name dept_name FROM tb1_emplyee e,tb1_dept d
WHERE e.d_id=d.id AND e.id=#{id}
</select>
使用<resultMap>标签封装结果集
<resultMap id="complexEmp" type="com.test.beans.Employee">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="email" property="email"/>
<result column="gender" property="gender"/>
<!--<association property="dept" javaType="com.test.beans.Department">
<id column="did" property="id"/>
<result column="dept_name" property="departmentName"/>
</association>-->
<result column="did" property="dept.id"></result>
<result column="dept_name" property="dept.departmentName"/>
</resultMap>
上边是使用通过级联属性的方式封装结果集
我们也可以通过association标签来完成同样的功能:
<resultMap id="complexEmp2" type="com.test.beans.Employee">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="email" property="email"/>
<result column="gender" property="gender"/>
<association property="dept" javaType="com.test.beans.Department">
<id column="did" property="id"/>
<result column="dept_name" property="departmentName"/>
</association>
</resultMap>
当然association标签的功能不止于此,还可以通过它实现分段查找的功能
上面的操作可以划分为下面的几步:
1、先按照员工id查询员工信息
2、根据查询员工信息中的d_id值去部门表查出部门信息
3、部门设置到员工中;
<select id="getEmpByIdStep" resultMap="MyEmpByStep">
select * from tb1_emplyee where id=#{id}
</select>
<resultMap type="com.test.beans.Employee" id="MyEmpByStep">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="email" property="email"/>
<result column="gender" property="gender"/>
<!-- association定义关联对象的封装规则
select:表明当前属性是调用select指定的方法查出的结果
column:指定将哪一列的值传给这个方法
流程:使用select指定的方法(传入column指定的这列参数的值)查出对象,并封装给property指定的属性
-->
<association property="dept"
select="com.test.dao.DepartMentMapper.getDeptById"
column="d_id">
</association>
</resultMap>
对应的Department映射文件:
<mapper namespace="com.test.dao.DepartMentMapper">
<select id="getDeptById" resultType="com.test.beans.Department">
SELECT id,dept_name departmentName FROM tb1_dept WHERE id=#{id}
</select>
</mapper>
注:对应的接口都没有给出,因为比较简单,自己实现一下即可。
当然association标签还可以实现懒加载的功能
什么是懒加载呢?
前面的分步查询,每查询一次都会执行两次sql(一次查询员工,一次查询部门)
有时候我们并不需要插叙部门的情况,所以懒查询就可以帮我们解决这个问题,提高效率,减少资源的占用
懒加载的实现也非常简单,只要在全局配置文件中添加如下的配置代码即可:
<settings>
<!--显示的指定每个我们需要更改的配置的值,即使他是默认的。防止版本更新带来的问题 -->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>