SSM——mybatis处理多表查询中 多对一 一对多 映射处理解决方案

SSM——mybatis处理多表查询中 多对一 映射处理的三种解决方案

案例分析:有员工 和 部门 两个实体 。表间关系为:一个部门对应多个员工 一个员工对应一个部门
需求:查询员工和部门信息,员工作为主表
注:如果只需要查看代码解决方案跳转到本文第3部分

1.准备工作

  • 员工数据表(t_emp)展示
    在这里插入图片描述
  • 插入4条数据
    在这里插入图片描述
  • 部门数据表(t_dept)展示
    在这里插入图片描述
  • 插入3条数据:
    在这里插入图片描述
    员工实体类创建
package com.b0.mybatis.pojo;
public class Emp {
    private Integer empId;
    private String empName;
    private Integer age;
    private String gender;
    private Dept dept;
    //避免篇幅过长,本文实体类需要读者自己构建getter、setter、构造器(无参构造,有参构造)、toString方法
}

部门实体类

package com.b0.mybatis.pojo;
public class Dept {
    private Integer deptId;
    private String deptName;
    //...
}

2.相关配置环境搭建

EmpMapper .java

package com.b0.mybatis.mapper;
public interface EmpMapper {
}

DeptMapper .java

package com.b0.mybatis.mapper;
public interface DeptMapper {
}
  • 搭建mapper配置文件,在resource目录下新建与mapper接口相同路径的目录(注意此处构建需要选择为目录,且在构建时多层目录用“/”分隔不能用“.”)

构建EmpMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- eg:namespace="com.b0.mybatis.mapper.UserMapper" -->
<mapper namespace="com.b0.mybatis.mapper.EmpMapper">
</mapper>

构建DeptMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- eg:namespace="com.b0.mybatis.mapper.UserMapper" -->
<mapper namespace="com.b0.mybatis.mapper.DeptMapper">
</mapper>

3.多对一映射处理

3.1 级联方式处理映射关系

1.EmpMapper .java中添加以下方法

    /**
     * 获取员工以及所对应的部门信息
     * @param empId
     * @return
     */
    Emp getEmpAndDeptByEmpId(@Param("empId")Integer empId);

2.EmpMapper.xml添加以下配置,完成级联映射配置

<!--    Emp getEmpAndDeptByEmpId(@Param("empId")Integer empId);-->
    <resultMap id="EmpAndDeptResultMapOne" type="Emp">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <result column="age" property="age"></result>
        <result column="gender" property="gender"></result>
        <!-- property:级联对应的是Emp类中的成员变量dept中的deptId属性 -->
        <result column="dept_id" property="dept.deptId"></result>
        <result column="dept_name" property="dept.deptName"></result>
    </resultMap>
	<select id="getEmpAndDeptByEmpId" resultMap="EmpAndDeptResultMapTwo">
        select
        t_emp.*,t_dept.*
        from t_emp
        left join t_dept
        on t_emp.dept_id = t_dept.dept_id
        where t_emp.emp_id = #{empId}
	</select>

3.2 使用association标签处理映射关系

1.EmpMapper .java同3.1一致
2.EmpMapper.xml添加以下配置,完成association映射关系配置

<!--    Emp getEmpAndDeptByEmpId(@Param("empId")Integer empId);-->
<!--
association:处理多对一的映射关系(也可以理解为:处理实体类类型的属性)
            property:设置需要处理映射关系的属性和属性名
            javaType:设置需要处理的属性的类型(注意:此处若核心配置文件没有配置默认别名,需要写入对应属性的全类名)
 -->
    <resultMap id="EmpAndDeptResultMapTwo" type="Emp">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <result column="age" property="age"></result>
        <result column="gender" property="gender"></result>
        <association property="dept" javaType="Dept">
            <id column="dept_id" property="deptId"></id>
            <result column="dept_name" property="deptName"></result>
        </association>
    </resultMap>
    <select id="getEmpAndDeptByEmpId" resultMap="EmpAndDeptResultMapTwo">
        select
        t_emp.*,t_dept.*
        from t_emp
        left join t_dept
        on t_emp.dept_id = t_dept.dept_id
        where t_emp.emp_id = #{empId}
    </select>

3.3 使用association 标签实现分步查询

优点:可以实现延迟加载。比如员工表与部门表联合查询,我们使用分步查询,在查询时若我们不需要部门信息,就可以使用延迟加载只查询员工信息,减少内存消耗。(实现方式放在文末讲解,先实现分步查询)
思路:第一步先根据员工ID查询出员工信息,第二步再根据员工信息中对应的部门ID从部门表中查询出部门数据。再编写时我们先拿到部门数据,方便我们查询员工以后再查询部门时更加便捷使用。实现如下:

1.查询部门信息
  • 编写DeptMapper.java文件中添加以下方法
	/**
     * 通过分布查询查询员工信息以及所对应部门信息的第二步
     * @return
     */
    Dept getEmpAndDeptByStepTwo(@Param("deptId") Integer deptId);
  • 编写DeptMapper.xml文件
<!--    Dept getEmpAndDeptByStepTwo(@Param("deptId") Integer deptId);-->
    <select id="getEmpAndDeptByStepTwo" resultType="Dept">
        select * from t_dept where dept_id = #{deptId}
    </select>
2.查询员工信息 多表联查 部门信息
  • 编写EmpMapper.java文件添加以下方法
/**
     * 通过分步查询员工以及所对应的部门信息
     * @param empId
     * @return
     */
    Emp getEmpAndDeptByStepOne(@Param("empId")Integer empId);
  • 编写EmpMapper.xml文件添加以下配置
<resultMap id="EmpAndDeptByStepResultMap" type="Emp">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <result column="age" property="age"></result>
        <result column="gender" property="gender"></result>
        <!--
             property:设置需要处理映射关系的属性的属性名
             select:设置分步查询的sql的唯一标识(即部门接口中对应方法的绝对路径)
             column:将查询出的某个字段作为分布查询的sql的条件
         -->
        <association property="dept"
                     select="com.b0.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
                     column="dept_id"><!-- colum属性相当于作为下一个语句的查询条件 -->
                     <!-- 此处select对应查询出来的结果与当前property属性是相对应的,此处为dept -->
        </association>
    </resultMap>
<!--    Emp getEmpAndDeptByStepOne(@Param("empId")Integer empId);-->
    <select id="getEmpAndDeptByStepOne" resultMap="EmpAndDeptByStepResultMap">
        select * from t_emp where emp_id = #{empId}
    </select>
3.延迟加载(懒加载)
  • 在核心配置文件中设置全局配置信息
<settings>
	<setting name="mapUnderscoreToCamelCase" value="true"/>
	<!-- 开启延迟加载 -->
	<setting name="lazyLoadingEnabled" value="true"/>
	<!-- 按需加载 -->
	<setting name="aggressiveLazyLoading" value="false"/>
</settings>
  • 属性讲解
    **lazyLoadingEnabled:开启延时加载(此处设置是针对全局文件进行懒加载)**设置为true时表示开启延迟加载,如上案例中我们只查询员工名称empName属性时只会执行一条查询员工的SQL语句。查看如下日志信息只执行一条SQL语句
DEBUG 10-13 15:05:09,214 ==>  Preparing: select * from t_emp where emp_id = ? (BaseJdbcLogger.java:137) 
DEBUG 10-13 15:05:09,267 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:137) 
DEBUG 10-13 15:05:09,375 <==      Total: 1 (BaseJdbcLogger.java:137) 

aggressiveLazyLoading:按需加载设置为true,会禁用懒加载,此时,我们仍然只查询员工名称empName查看日志信息,执行了两条SQL语句,懒加载被禁用。

DEBUG 10-13 15:09:44,270 ==>  Preparing: select * from t_emp where emp_id = ? (BaseJdbcLogger.java:137) 
DEBUG 10-13 15:09:44,315 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:137) 
DEBUG 10-13 15:09:44,416 <==      Total: 1 (BaseJdbcLogger.java:137) 
DEBUG 10-13 15:09:44,419 ==>  Preparing: select * from t_dept where dept_id = ? (BaseJdbcLogger.java:137) 
DEBUG 10-13 15:09:44,420 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:137) 
DEBUG 10-13 15:09:44,423 <==      Total: 1 (BaseJdbcLogger.java:137) 
4.懒加载开启全局处理后-部分语句不使用懒加载情况处理

前面我们提到若在全局配置文件中开启了延迟加载,那么所有的查询都会懒加载,但是若我们有需求:需要在部分查询语句中不使用懒加载,需要加载所有数据。如何解决?
在我们resultMap标签的子标签association标签中配置fetchType属性

<association property="dept" fetchType="lazy"
                     select="com.b0.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
                     column="dept_id"><!-- colum属性相当于作为下一个语句的查询条件 -->
</association>

fetchType=“eager(立即加载)/lazy(延迟加载)”

4.一对多映射处理

4.1 使用collection标签处理映射关系

需求:查询部门和员工信息,部门作为主表
分析:部门与员工关系 是 一对多
部门类中 一个部门 对应 多个员工 -->即一个员工集合 一对多:对多对应的是一个集合 类中需要新增一个集合存放查询出来的多个员工信息
1.修改Dept.java新增一个Emp类型的集合命名为emps

public class Dept {
    private Integer deptId;
    private String deptName;
    private List<Emp> emps;
    //避免篇幅过长,本文实体类需要读者自己构建getter、setter、构造器(无参构造,有参构造)、toString方法
}

2.编写DeptMapper.java接口,新增方法

/**
     * 查询部门以及部门中的员工信息
     * @param deptId
     * @return
     */
    Dept getDeptAndEmpByDeptId(@Param("deptId") Integer deptId);

3.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" ofType="Emp"><!-- ofType表示:集合中的类型 -->
            <id column="emp_id" property="empId"></id>
            <result column="emp_name" property="empName"></result>
            <result column="age" property="age"></result>
            <result column="gender" property="gender"></result>
        </collection>
    </resultMap>
<!--    Dept getDeptAndEmpByDeptId(@Param("deptId") Integer deptId);-->
    <select id="getDeptAndEmpByDeptId" resultMap="deptAndEmpResultMap">
        select * from t_dept
        left join t_emp on t_dept.dept_id = t_emp.dept_id
        where t_dept.dept_id = #{deptId}
    </select>
4.2 使用collection标签分步查询

思路:第一步先根据部门ID查询出部门信息,第二步再根据部门ID在员工表中通过部门ID从员工表中查询出员工数据。实现如下:

1.Dept.java新增一个Emp类型的集合命名为emps

加强理解:此处提供一个集合变量实现了一对多的联系。

public class Dept {
    private Integer deptId;
    private String deptName;
    private List<Emp> emps;
    //避免篇幅过长,本文实体类需要读者自己构建getter、setter、构造器(无参构造,有参构造)、toString方法
}
2.第一步:编写DeptMapper接口
/**
     * 通过分步查询查询部门以及部门中的员工信息的第一步
     * @param deptId
     * @return
     */
    Dept getDeptAndEmpByStepOne(@Param("deptId") Integer deptId);
3.第一步:编写DeptMapper.xml配置实现文件
<resultMap id="deptAndEmpResultMapByStep" type="Dept">
        <id column="dept_id" property="deptId"></id>
        <result column="dept_name" property="deptName"></result>
        <collection property="emps"
                    select="com.b0.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
                    column="dept_id"></collection><!-- colum属性相当于作为下一个语句的查询条件 -->
                    <!-- 此处select对应查询出来的结果与当前标签property属性是相对应的,此处为集合 -->
    </resultMap>
<!--    Dept getDeptAndEmpByStepOne(@Param("deptId") Integer deptId);-->
    <select id="getDeptAndEmpByStepOne" resultMap="deptAndEmpResultMapByStep">
        select * from t_dept where dept_id = #{deptId}
    </select>
4.第二步:编写查询接口返回一个Emp类型的集合
/**
     * 通过分步查询查询部门以及所对应的员工信息的第二步
     * @param deptId
     * @return
     */
    List<Emp> getDeptAndEmpByStepTwo(@Param("deptId") Integer deptId);
5.第二步:根据部门ID查询用户信息返回生成一个集合
<!--    List<Emp> getDeptAndEmpByStepTwo(@Param("deptId") Integer deptId);-->
    <select id="getDeptAndEmpByStepTwo" resultType="Emp">
        select * from t_emp where dept_id = #{deptId}
    </select>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值