创建数据库对应的实体类,分步查询要基于至少两个表
1.员工表实体类
//员工实体类
public class Emp {
private Integer empId;
private String empName;
private Integer age;
private String sex;
//一个员工只属于一个部门,多个员工可以同属于一个部门
private Dept dept;
2.部门表实体类
//部门实体类
public class Dept {
private Integer deptId;
private String deptName;
//一个部门有多个员工
private List<Emp> emps;
多对一,是对象;一对多,是集合
多对一场景:查询员工信息及其所在的部门信息
分步查询第①步:通过分步查询,查询员工信息
EmpMapper接口中的方法为
/**
* 分布查询第一步:根据empId查询员工dept信息
* @param empId
* @return
*/
Emp getEmpAndDeptStep(@Param("empId") Integer empId);
映射文件EmpMapper.xml为
<!--
id:resultMap的唯一标识
type:所要处理的实体类
association:一个复杂类型的关联,在这个场景中就是emp类型和dept类型的关联
property:关联的属性名,首次分步查询的结果名
select:下一次分步查询sql语句的唯一标识;即全类名+id
column:下一次分步查询sql语句的主键
-->
<resultMap id="getEmpAndDeptByStep" type="Emp">
<association property="dept"
select="com.yuuu.mybatis.mapper.DeptMapper.getEmpAndDeptStep"
column="dept_id"
></association>
</resultMap>
<!-- Emp getEmpAndDeptStep(@Param("empId") Integer empId);-->
<select id="getEmpAndDeptStep" resultMap="getEmpAndDeptByStep">
select * from t_emp where emp_id = #{empId}
</select>
分步查询第②步:根据员工所对应的dept_id查询部门信息
DeptMapper接口中的方法为
/**
* 分布查询第二步,根据deptId查询部门
* @param deptId
* @return
*/
Dept getEmpAndDeptStep(@Param("deptId") Integer deptId);
Dept getEmpAndDeptStep(@Param("deptId") Integer deptId);
映射文件DeptMapper.xml为
<!-- Dept getEmpAndDeptStep(@Param("deptId") Integer deptId);-->
<!--根据deptId查询部门信息,所以直接使用resultType即可-->
<select id="getEmpAndDeptStep" resultType="Dept">
select * from t_dept where dept_id = #{deptId}
</select>
这样就可以查询到员工的详细信息了
下面是一对多场景:查询一个部门中的所有员工
分步查询第①步:根据deptId查找部门
DeptMapper接口中的方法为
/**
* 分布查询第一步,根据deptId查找部门
* @param deptId
* @return
*/
Dept getDeptAndEmpStep(@Param("deptId") Integer deptId);
映射文件DeptMapper.xml为
<!--和多对一类似,不过这里使用的关键字为collection,集合-->
<resultMap id="DeptAndEmpResultMap" type="Dept">
<id column="dept_id" property="deptId"></id>
<result column="dept_name" property="deptName"></result>
<collection property="emps"
select="com.yuuu.mybatis.mapper.EmpMapper.getDeptAndEmpStep"
column="dept_id"
></collection>
</resultMap>
<!-- Dept getDeptAndEmpStep(@Param("deptId") Integer deptId);;-->
<select id="getDeptAndEmpStep" resultMap="DeptAndEmpResultMap">
select dept_id,dept_name from t_dept where dept_id = #{deptId}
</select>
分步查询第②步:根据查找到的部门的deptId查找员工
EmpMapper接口中的方法为
/**
* 分布查询第二步,根据查找到的部门的deptId查找员工
* @param deptId
* @return
*/
List<Emp> getDeptAndEmpStep(@Param("deptId") Integer deptId);
映射文件EmpMapper.xml为
<!-- List<Emp> getDeptAndEmpStep(@Param("deptId") Integer deptId);-->
<select id="getDeptAndEmpStep" resultType="Emp">
select * from t_emp where dept_id = #{deptId}
</select>
这样,就可以查到某个部门的所有员工了
总结:分步查询步骤比较固定,但是理解起来可能需要点时间,以后多操作就可以了,还是要记住上面说的:多对一,是对象;一对多,是集合。
一起学习,共同进步!
青青子衿,悠悠我心。
纵我不往,子宁不嗣音?
青青子佩,悠悠我思。
纵我不往,子宁不来?
挑兮达兮,在城阙兮。
一日不见,如三月兮。