前言: 在项目中,某些实体类之间肯定有关键关系,比如一对一,一对多等。在hibernate 中用one to one和one to many,而mybatis 中就用association和collection。
分步查询
association: 一对一关联(has one)
分步查询第一步
EmpMapper接口
/**
* 通过分步查询 查询员工所对应的部门信息
* 分步查询 第一步
*/
Emp getEmpAndDeptByStepOne(@Param("eid") Integer eid);
则相对相应的 EmpMapper.xml
<!-- Emp getEmpAndDeptByStepOne(@Param("eid") Integer eid);-->
<!-- *** 处理多对一映射3 分步查询
select:设置分步查询sql的唯一标识 "mapper的全类名"
column:需要分布查询的属性名
fetchType:开启了延迟记载 通过此属性控制
eager:立即加载
lazy:延迟加载
-->
<resultMap id="empAndDeptByStepResultMap" type="com.chen.mybatis.entity.Emp">
<id property="eid" column="eid"></id>
<result property="empName" column="emp_name"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
<result property="email" column="email"></result>
<collection property="dept"
select="com.chen.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
column="did"
fetchType="lazy">
</collection>
</resultMap>
<select id="getEmpAndDeptByStepOne" resultMap="empAndDeptByStepResultMap">
select * from t_emp where eid=#{eid}
</select>
分步查询第二步
DeptMapper接口
/**
* 通过分步查询 查询员工所对应的部门信息
* 分步查询 第二步
*/
Dept getEmpAndDeptByStepTwo(@Param("did") Integer did);
则相对相应的 DeptMapper.xml
<!-- Dept getEmpAndDeptByStepTwo(@Param("did") Integer did);-->
<select id="getEmpAndDeptByStepTwo" resultType="com.chen.mybatis.entity.Dept">
select * from t_dept where did =#{did}
</select>
collection:一对多关联(has many)
分步查询第一步
DeptMapper接口
/**
* 获取部门的所有员工信息
* 分步查询 第一步
*/
Dept getDeptAndEmpByStepOne(@Param("did")Integer did);
相对应的DeptMapper.xml
<!-- Dept getDeptAndEmpByStepOne(@Param("did")Integer did);-->
<resultMap id="DeptAndEmpByStepResultMap" type="com.chen.mybatis.entity.Dept">
<id property="did" column="did"></id>
<result property="deptName" column="dept_name"></result>
<collection property="emps"
select="com.chen.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
column="did">
</collection>
</resultMap>
<select id="getDeptAndEmpByStepOne" resultMap="DeptAndEmpByStepResultMap">
select * from t_dept where did=#{did}
</select>
分步查询第二步
EmpMapper接口
/**
* 获取部门的所有员工信息
* 分步查询 第二步
*/
List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);
相对应的xml EmpMapper.xml
<!-- List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);-->
<select id="getDeptAndEmpByStepTwo" resultType="com.chen.mybatis.entity.Emp">
select *
from t_emp where did=#{did};
</select>
总结
1、collection:一对多关联(has many)
2、association: 一对一关联(has one)
3、全局配置 驼峰式命名自动转换的配置 与开启延迟查询
<!-- 全局配置 驼峰式命名自动转换的配置 -->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 开启延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
</settings>