association:用于对象间包含关系映射
方式一:通过association标签来封装结果集
<mapper namespace="org.apache.ibatis.submitted.associationtest.Mapper"> <resultMap type="org.apache.ibatis.submitted.associationtest.Car" id="carResult"> <id column="carid" property="id"/> <result column="cartype" property="type"/> <association property="engine" resultMap="engineResult"/> <association property="brakes" resultMap="brakesResult"/> </resultMap> <resultMap type="org.apache.ibatis.submitted.associationtest.Engine" id="engineResult"> <result column="enginetype" property="type"/> <result column="enginecylinders" property="cylinders"/> </resultMap> <resultMap type="org.apache.ibatis.submitted.associationtest.Brakes" id="brakesResult"> <result column="brakesType" property="type"/> </resultMap> <select id="getCars" resultMap="carResult"> select * from cars </select> <select id="getCarsNonUnique" resultMap="carResult"> select 1 as carid, cartype, enginetype, enginecylinders, brakestype from cars </select> <select id="getCars2" resultMap="carResult"> select 1 as carid, cartype, enginetype, enginecylinders, brakestype from cars where carid in (1,2) </select> </mapper>
查询:
<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>
方式二:通过association标签实现分段查找
<resultMap id="MyEmpByStep" 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定义关联对象的封装规则 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>
查询:
<select id="getEmpByIdStep" resultMap="MyEmpByStep"> select * from tb1_emplyee where id=#{id} </select>
association标签还可以实现懒加载的功能
什么是懒加载呢?
前面的分步查询,每查询一次都会执行两次sql(一次查询员工,一次查询部门)
有时候我们并不需要插叙部门的情况,所以懒查询就可以帮我们解决这个问题,提高效率,减少资源的占用
懒加载的实现也非常简单,只要在全局配置文件中添加如下的配置代码即可:
<settings> <!--显示的指定每个我们需要更改的配置的值,即使他是默认的。防止版本更新带来的问题 --> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> </settings>