8. 自定义映射resultMap
阅读原文时间:2023年08月11日阅读:1

在 Mybatis 中,resultType 和 resultMap 都用于定义查询结果的映射关系。它们的使用场景如下:

  1. resultType

resultType 用于指定返回结果的数据类型,通常用于返回简单类型的结果以及返回 vo 或 dto 等自定义类型的结果。例如:

<select id="findUserById" parameterType="int" resultType="com.example.User">
  select * from user where id = #{id}
</select>

这里 resultType 指定了查询结果将以 com.example.User 类型返回,Mybatis 会自动将查询结果映射到 User 对象中。resultType 适用于简单的查询操作,能够方便快捷地获取数据库表中的数据,并且使用起来比较简单。

  1. resultMap

resultMap 用于自定义查询结果的映射规则,通常用于处理复杂的查询结果,或者需要使用嵌套查询等复杂查询操作。例如:

<resultMap id="userResultMap" type="com.example.User">
  <id property="id" column="user_id" />
  <result property="username" column="user_name" />
  <result property="email" column="user_email" />
  <association property="orders" javaType="list" resultMap="orderResultMap" />
</resultMap>

<resultMap id="orderResultMap" type="com.example.Order">
  <id property="id" column="order_id" />
  <result property="amount" column="order_amount" />
  <result property="createTime" column="create_time" />
</resultMap>

<select id="findUserById" parameterType="int" resultMap="userResultMap">
  select u.id as user_id, u.username as user_name, u.email as user_email,
  o.id as order_id, o.amount as order_amount, o.create_time
  from user u left join order o on u.id = o.user_id
  where u.id = #{id}
</select>

这里 resultMap 定义了 User 类型和 Order 类型的结果映射规则,Mybatis 会根据这些规则将复杂的查询结果映射到对应的 Java 类型中。对于复杂的查询操作,使用 resultMap 可以很好地处理查询结果中的各种细节,支持结果的拼接、嵌套等操作,使查询逻辑更加清晰。

1. resultMap 处理字段和属性的映射关系

若字段名和实体类中的属性名不一致,则可以通过 resultMap 设置自定义映射

<!--
    resultMap:设置自定义映射
    属性:
    id:表示自定义映射的唯一标识
    type:查询的数据要映射的实体类的类型
    子标签:
    id:设置主键的映射关系
    result:设置普通字段的映射关系
    association:设置多对一的映射关系
    collection:设置一对多的映射关系
    属性:
    property:设置映射关系中实体类中的属性名
    column:设置映射关系中表中的字段名
-->
<resultMap id="userMap" type="User">
    <id property="id" column="id"></id>
    <result property="userName" column="user_name"></result>
    <result property="password" column="password"></result>
    <result property="age" column="age"></result>
    <result property="sex" column="sex"></result>
</resultMap>
<!--List<User> testMohu(@Param("mohu") String mohu);-->
<select id="testMohu" resultMap="userMap">
    <!--select * from t_user where username like '%${mohu}%'-->
select id,user_name,password,age,sex from t_user where user_name likeconcat('%',#{mohu},'%')
</select>

  • resultMap:设置自定义映射

  • 属性:

    • id:表示自定义映射的唯一标识
    • type:查询的数据要映射的实体类的类型
  • 子标签 :

    • id:设置主键的映射关系
    • result:设置普通字段的映射关系
    • association:设置多对一的映射关系
    • collection:设置一对多的映射关系
  • 属性 :

    • property:设置映射关系中实体类中的属性名
    • column:设置映射关系中表中的字段名

若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用_),实体类中的属性名符合 Java 的规则(使用驼峰)此时也可通过以下两种方式处理字段名和实体类中的属性的映射关系:

  1. 可以通过为字段起别名的方式,保证和实体类中的属性名保持一致
  2. 可以在 MyBatis 的核心配置文件中设置一个全局配置信息 mapUnderscoreToCamelCase,可

以在查询表中数据时,自动将_类型的字段名转换为驼峰

例如:字段名 user_name,设置了 mapUnderscoreToCamelCase,此时字段名就会转换为 userName

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

2. 多对一映射处理

场景模拟: 查询员工信息以及员工所对应的部门信息

语法显示: (注意 column 和 property 的位置)

    <resultMap id="empAndDeptByEmpId" 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>
        <result column="dept_id" property="dept.deptId"></result>
        <result column="dept_name" property="dept.deptName"></result>
    </resultMap>

    <select id="getEmpAndDeptById" resultMap="empAndDeptByEmpId">
        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>

    <resultMap id="empAndDeptByEmpIdTwo" 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">
            <result column="dept_id" property="deptId"></result>
            <result column="dept_name" property="deptName"></result>
        </association>
    </resultMap>

    <select id="getEmpAndDeptById" resultMap="empAndDeptByEmpIdTwo">
        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>

  • association : 处理多对一的映射关系 (处理实体类型的属性)
  • property : 设置需处理映射关系的属性的属性名
  • JavaType : 设置要处理的属性的类型

① 查询员工信息

代码示例 :

    /**
     * 通过分步查询员工信息
     * @param empId
     * @return
     */
    Emp getEmpByStep(@Param("empId") Integer empId);

    <resultMap id="empDeptSteMap" 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"
                     select="com.north.mybatis.mapper.DeptMapper.getEmpDeptByStep"
                     column="dept_id"
                     ></association>
    </resultMap>

        <!--
        select:设置分步查询,查询某个属性的值的sql的标识(namespace.sqlId)
        column:将sql以及查询结果中的某个字段设置为分步查询的条件
    -->

    <select id="getEmpByStep" resultMap="empDeptSteMap">
        select * from t_emp where emp_id = #{empId}
    </select>

② 根据员工所对应的部门 id 查询部门信息

代码示例如下 :

    /**
     * 分步查询的第二步: 根据员工所对应的did查询部门信息
     * @param deptId
     * @return
     */
    Dept getEmpDeptByStep(@Param("deptId") Integer deptId);

        <select id="getEmpDeptByStep" resultType="Dept">
            select * from t_dept where dept_id  = #{deptId}
        </select>

3. 延迟加载

Mybatis 中的延迟加载指的是在查询主体对象时,只查询主体对象的信息,而对于关联的属性或集合对象,直到访问这些对象时才会进行查询操作,以达到减少查询次数、提高性能的目的。

延迟加载的作用是:

  1. 减少查询次数:当需要查询的数据量较大时,可以通过延迟加载避免一次性查询所有的数据,大大降低数据库的负载和查询时间,提高查询效率。
  2. 避免冗余数据:当主体对象包含多个关联属性或集合对象时,如果一次性加载所有数据,有可能会产生冗余的查询数据,而使用延迟加载可避免这种情况的出现,节省资源。
  3. 提升性能:当关联对象比较复杂时,一次性加载所有数据可能会显著降低程序的运行效率,使用延迟加载技术可以避免这种问题,并提高程序的运行速度。

延迟加载在 Mybatis 中的实现是通过动态代理实现的,Mybatis 在查询主体对象时,只返回代理对象,当第一次访问代理对象的相关属性时,会触发查询操作,从而实现延迟加载的效果。不过需要注意的是,Mybatis 中延迟加载的实现需要依赖于持久化框架和数据库的支持,如果底层不支持延迟加载,Mybatis 的延迟加载技术则无法实现,需要采取其他的手段进行基于性能的优化。

4. 一对多映射处理

/**
* 根据部门id查新部门以及部门中的员工信息
* @param did
* @return
*/
Dept getDeptEmpByDid(@Param("did") int did);


<resultMap id="deptEmpMap" type="Dept">
 &nbsp; &nbsp;<id property="did" column="did"></id>
 &nbsp; &nbsp;<result property="dname" column="dname"></result>
 &nbsp; &nbsp;<!--
        ofType:设置collection标签所处理的集合属性中存储数据的类型
    -->
    <collection property="emps" ofType="Emp">
 &nbsp; &nbsp; &nbsp; &nbsp;<id property="eid" column="eid"></id>
 &nbsp; &nbsp; &nbsp; &nbsp;<result property="ename" column="ename"></result>
 &nbsp; &nbsp; &nbsp; &nbsp;<result property="age" column="age"></result>
 &nbsp; &nbsp; &nbsp; &nbsp;<result property="sex" column="sex"></result>
    </collection>
</resultMap>
<!--Dept getDeptEmpByDid(@Param("did") int did);-->
<select id="getDeptEmpByDid" resultMap="deptEmpMap">
    select dept.*,emp.* from t_dept dept left join t_emp emp on dept.did =emp.did where dept.did = #{did}
</select>

① 查询部门信息

/**
* 分步查询部门和部门中的员工
* @param did
* @return
*/
Dept getDeptByStep(@Param("did") int did);


<resultMap id="deptEmpStep" type="Dept">
 &nbsp; &nbsp;<id property="did" column="did"></id>
 &nbsp; &nbsp;<result property="dname" column="dname"></result>
 &nbsp; &nbsp;<collection property="emps" fetchType="eager"select="com.atguigu.MyBatis.mapper.EmpMapper.getEmpListByDid" column="did">
    </collection>
</resultMap>
<!--Dept getDeptByStep(@Param("did") int did);-->
<select id="getDeptByStep" resultMap="deptEmpStep">
    select * from t_dept where did = #{did}
</select>

② 根据部门 id 查询部门中的所有员工

/**
* 根据部门id查询员工信息
* @param did
* @return
*/
List<Emp> getEmpListByDid(@Param("did") int did);


<!--List<Emp> getEmpListByDid(@Param("did") int did);-->
<select id="getEmpListByDid" resultType="Emp">
    select * from t_emp where did = #{did}
</select>

分步查询的优点:可以实现延迟加载

但是必须在核心配置文件中设置全局配置信息:

lazyLoadingEnabled:延迟加载的全局开关。当开启时,所有关联对象都会延迟加载

aggressiveLazyLoading:当开启时,任何方法的调用都会加载该对象的所有属性。否则,每个属性会按需加载

此时就可以实现按需加载,获取的数据是什么,就只会执行相应的 sql。此时可通过 association 和

collection 中的 fetchType 属性设置当前的分步查询是否使用延迟加载, fetchType="lazy(延迟加

载)|eager(立即加载)"