MyBatis学习笔记(九) —— 自定义映射resultMap

news2024/9/29 23:33:21

9、自定义映射resultMap

9.1、resultMap处理字段和属性的映射关系

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

resultType 是一个具体的类型。

resultMap 是resultMap的标签。

id 是处理主键和属性的映射关系;

result 是处理普通字段和属性的映射关系;

association 是处理多对一

collection 是处理一对多

property 属性

column 字段

javaType 属性的类型

jdbcType 字段的类型

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

    <!--
        字段名和属性不一致的情况,如何处理映射关系
        1、为查询的字段设置别名,和属性名保持一致
        2、当字段符合MySQL的要求使用_,而属性符合java的要求使用驼峰
        此时可以在MyBatis的核心配置文件中设置一个全局设置,可以自动将下划线映射为驼峰
        emp_id:empId, emp_name:empName
        3、使用resultMap自定义映射处理
        处理多对一的映射关系:
        ① 级联方式处理
        ② association
        ③ 分步查询

        处理一对多的映射关系
        ① collection
        ② 分步查询
     -->
    
    <!--
        resultMap: 设置自定义的映射关系
        id: 唯一标识
        type: 处理映射关系的实体类的类型
        常用的标签:
        id: 处理主键和实体类中实现的映射关系
        result: 处理普通字段和实体类中属性的映射关系
        association: 处理多对一的映射关系(处理实体类类型的属性)
        collection: 处理一对多的映射关系(处理集合类型的属性)
        column: 设置映射关系中的字段名,必须是sql查询出的某个字段
        property: 设置映射关系中的属性的属性名,必须是处理的实体类类型中的属性名
     -->
    <resultMap id="empResultMap" 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>
    </resultMap>

    <select id="getEmpByEmpId" resultMap="empResultMap">
        select * from t_emp where emp_id = #{empId}
    </select>
</mapper>

select标签中的resultMap的值对应的是resultMap标签的id

img

9.2、多对一映射处理

处理多对一的映射关系的三种方式:

① 级联方式处理

② association

③ 分步查询

场景模拟:

查询员工信息以及员工所对应的部门信息

Dept.java

package com.fan.mybatis.pojo;

/**
 * @Date: 2023/02/27
 * @Author: fan
 * @Description:
 */
public class Dept {
    private Integer deptId;

    private String deptName;

    public Dept() {
    }

    public Dept(Integer deptId, String deptName) {
        this.deptId = deptId;
        this.deptName = deptName;
    }

    public Integer getDeptId() {
        return deptId;
    }

    public void setDeptId(Integer deptId) {
        this.deptId = deptId;
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }

    @Override
    public String toString() {
        return "Dept{" +
                "deptId=" + deptId +
                ", deptName='" + deptName + '\'' +
                '}';
    }
}

Emp.java

package com.fan.mybatis.pojo;

/**
 * @Date: 2023/02/27
 * @Author: fan
 * @Description:
 */
public class Emp {
    private Integer empId;
    private String empName;
    private Integer age;
    private String gender;

    public Dept getDept() {
        return dept;
    }

    public void setDept(Dept dept) {
        this.dept = dept;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "empId=" + empId +
                ", empName='" + empName + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", dept=" + dept +
                '}';
    }

    private Dept dept;

    public Emp() {
    }

    public Emp(Integer empId, String empName, Integer age, String gender) {
        this.empId = empId;
        this.empName = empName;
        this.age = age;
        this.gender = gender;
    }

    public Integer getEmpId() {
        return empId;
    }

    public void setEmpId(Integer empId) {
        this.empId = empId;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

}

EmpMapper.java

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

ResultMapTest.java

@Test
public void testGetEmpAndDeptByEmpId(){
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
    Emp emp = mapper.getEmpAndDeptByEmpId(1);
    System.out.println(emp);
}

9.2.1、方式1:级联方式

第一种方式:使用级联的方式处理多对一的映射关系

EmpMapper.xml

<resultMap id="empAndDeptResultMap" 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="getEmpAndDeptByEmpId" resultMap="empAndDeptResultMap">
  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>

运行测试:

img

9.2.2、方式2:association

第二种方式:使用 association 处理多对一的映射

<resultMap id="empAndDeptResultMap" 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: 设置需要处理映射关系的属性的属性名
    javaType: 设置要处理的属性的类型
  -->
  <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="empAndDeptResultMap">
  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>

9.2.3、方式3:分布查询

第三种方式:使用分布查询处理多对一的映射关系

分布查询:即分步骤查询,比如可以先把员工信息查询出来,然后把员工对应部门的id作为条件,在部门表里查询出员工对应的部门。

多表联查的环境中,通过多个sql语句,一步一步的把需要的数据查询出来。

分布查询可以处理多对一、一对多的映射关系

DeptMapper.java

package com.fan.mybatis.mapper;

import com.fan.mybatis.pojo.Dept;
import org.apache.ibatis.annotations.Param;

public interface DeptMapper {
    /**
     * 通过分步查询查询员工以及所对应的部门信息的第二步
     * @return
     */
    Dept getEmpAndDeptByStepTwo(@Param("deptId") Integer deptId);
}

DeptMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fan.mybatis.mapper.DeptMapper">
    
    <select id="getEmpAndDeptByStepTwo" resultType="Dept">
        select * from t_dept where dept_id = #{deptId}
    </select>
</mapper>

EmpMapper.java

/**
* 通过分布查询查询员工以及所对应的部门信息的第一步
* @param empId
* @return
*/
Emp getEmpAndDeptByStep(@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的唯一标识(namespace.sqlId)
    column: 将查询出来的某个字段作为查询的sql的条件
  -->
  <association property="dept"
    select="com.fan.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
    column="dept_id">
  </association>
</resultMap>

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

ResultMapTest.java

@Test
public void testGetEmpAndDeptByStep(){
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
    Emp emp = mapper.getEmpAndDeptByStepOne(1);
    System.out.println(emp);
}

9.3、延迟加载

分步查询的优点:可以实现延迟加载,延迟加载也可以称为懒加载。

延迟加载可以节约计算机资源,不必要的数据不查询。

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

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

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

此时就可以实现按需加载,获取的数据是什么,就只会执行相应的sql。此时可通过association和collection中的fetchType属性设置当前的分布查询是否使用延迟加载,fetchType=“lazy(延迟加载)|eager(立即加载)”

9.3.1全局配置延迟加载

<!-- 开启延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 按需加载 -->
<setting name="aggressiveLazyLoading" value="false"/>

img

@Test
public void testGetEmpAndDeptByStep(){
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
    Emp emp = mapper.getEmpAndDeptByStepOne(1);
    System.out.println(emp.getEmpName());
}

运行测试,可以看到只执行了员工的sql

img

如果去掉延迟加载的代码

img

运行测试,可以看到执行了2条sql,员工和部门的sq

img

以上是全局配置加载延迟,对mybatis所有的分步查询都有作用。

9.3.2、设置当前分步查询是否延迟加载

如果让某个分步查询来实现完整的延迟加载,可以添加 fetchType=“eager” 立即加载,或者,fetchType=“lazy” 懒加载

img

img

9.4、一对多映射处理

处理一对多的映射关系

① collection

② 分步查询

场景模拟:

查询某个部门的员工信息,部门对员工是一对多。

9.4.1、方式1:collection

Dept.java

package com.fan.mybatis.pojo;

import java.util.List;

/**
 * @Date: 2023/02/27
 * @Author: fan
 * @Description:
 */
public class Dept {
    private Integer deptId;

    private String deptName;

    private List<Emp> emps;

    public Dept() {
    }

    public Dept(Integer deptId, String deptName) {
        this.deptId = deptId;
        this.deptName = deptName;
    }

    public Integer getDeptId() {
        return deptId;
    }

    public void setDeptId(Integer deptId) {
        this.deptId = deptId;
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }

    public List<Emp> getEmps() {
        return emps;
    }

    public void setEmps(List<Emp> emps) {
        this.emps = emps;
    }

    @Override
    public String toString() {
        return "Dept{" +
                "deptId=" + deptId +
                ", deptName='" + deptName + '\'' +
                ", emps=" + emps +
                '}';
    }
}

DeptMapper.java

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

collection标签的ofType, 设置集合中的属性

association 标签的javaType,是设置属性的类型

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fan.mybatis.mapper.DeptMapper">
    
    <resultMap id="deptAndEmpResultMap" type="Dept">
        <id column="dept_id" property="deptId"></id>
        <result column="dept_name" property="deptName"></result>
        <!--
            ofType: 设置集合类型的属性中存储的数据的类型
         -->
        <collection property="emps" ofType="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>
        </collection>
    </resultMap>

    <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>
</mapper>

ResultMapTest.java

@Test
public void testGetDeptAndEmpByDeptId(){
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);
    Dept dept = mapper.getDeptAndEmpByDeptId(1);
    System.out.println(dept);
}

运行测试

img

9.4.2、方式2:分步查询

第二种方式:分步查询处理一对多的映射关系

DeptMapper.java

/**
* 通过分步查询查询部门以及部门中的员工信息的第一步
* @param deptId
* @return
*/
Dept getDeptAndEmpByStepOne(@Param("deptId") Integer deptId);

EmpMapper.java

/**
* 通过分步查询查询部门以及部门中的员工信息的第二步
* @param deptId
* @return
*/
List<Emp> getDeptAndEmpByStepTwo(@Param("deptId") Integer deptId);

EmpMapper.xml

<select id="getDeptAndEmpByStepTwo" resultType="Emp">
  select * from t_emp where dept_id = #{deptId}
</select>

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.fan.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
    column="dept_id"></collection>
</resultMap>

<select id="getDeptAndEmpByStepOne" resultMap="deptAndEmpResultMapByStep">
  select * from t_dept where dept_id = #{deptId}
</select>

ResultMapTest.java

@Test
public void testGetDeptAndEmpByStep(){
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);
    Dept dept = mapper.getDeptAndEmpByStepOne(1);
    System.out.println(dept);
}

运行测试:

img

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/381169.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

FirePower X2 14.0.1 for RAD Studio Alexandria

介绍 FirePower X2 FirePower X2 集成了 RAD Studio 11.0 Alexandria 中的新功能&#xff0c;并预览了我们的新特色组件 TwwDataGrouper。 FirePower X2 还允许您为 Apple 的新 M1 芯片构建应用程序&#xff0c;这样您就可以进一步利用 M1 芯片来提高本机应用程序的性能&#x…

set和map的基本使用

目录 关联式容器 要点分析 键值对 pair介绍 set 模板参数列表&#xff1a; set的构造&#xff1a; 常用接口 操作 multiset map map的构造 插入 make_pair map的迭代器 operator[] multimap multimap中为什么没有重载operator[] 关联式容器 关联式容器也是用…

(五十六)针对主键之外的字段建立的二级索引,又是如何运作的?

上一次我们已经给大家彻底讲透了聚簇索引这个东西&#xff0c;其实聚簇索引就是innodb存储引擎默认给我们创建的一套基于主键的索引结构&#xff0c;而且我们表里的数据就是直接放在聚簇索引里的&#xff0c;作为叶子节点的数据页&#xff0c;如下图。 而且我们现在也对基于主键…

日志框架以及如何使用LogBack记录程序

使用日志框架可以记录一个程序运行的过程和详情&#xff0c;同时便捷地存储到文件里面&#xff0c;并且性能和灵活性都比较好。日志的体系结构包括两类日志规范接口&#xff1a;Commons Logging&#xff0c;简称&#xff1a;JCL&#xff1b;Simple Logging Facade for Java&…

JavaScript高级程序设计读书分享之8章——8.2创建对象

JavaScript高级程序设计(第4版)读书分享笔记记录 适用于刚入门前端的同志 创建Object的实例 let person new Object(); person.name "Nicholas"; person.age 29; person.job "Software Engineer"; person.sayName function() { console.log(this…

增长乏力?创造产品和项目需求的6大方法【一杯咖啡谈项目】

我这里所说的创造需求&#xff0c;类似于PMI在《需求管理实践指南》中所写的专业术语“需要评估”&#xff08;needs assessment&#xff09;&#xff0c;这个需要评估&#xff0c;没有写进PMI的《项目管理知识体系指南&#xff08;PMBOK指南&#xff09;》&#xff08;以下称为…

fork()出来一个进程,这个进程的父进程是从哪来的?

基本概念fork() creates a new process by duplicating the calling process. The new process is referred to as the child process. The calling process is referred to as the parent process.fork()是一个系统调用&#xff0c;不是一个函数。详细信息可以&#xff0c;man…

day(22) Echarts和nacos

day(22) Echarts和nacos一、Echarts和nacos1.1 数据展示1.2 查询日期之间的数据二、配置中心2.1 配置中心spring cloud config2.1.1 缺点2.1.2 其他配置中心2.2 nacos2.2.1 pom2.2.2 配置文件2.2.3 Data id是微服务名称2.2.4 优先级2.2.5 动态刷新2.2.6 namespace2.2.7 多配置文…

Symbiosis Nest 共生巢token跨链兑换协议

参考文献&#xff1a; Getting Started with Symbiosis - Symbiosis Documentation Relayers Network | Symbiosis - Symbiosis Documentation Symbiosis V1 vs. V2 - Symbiosis Documentation Symbiosis protocal 基于稳定币的跨链兑换协议. Symbiosis protocol 组成结构…

pyechart绘制多图(三图及以上)的overlap叠加

pyechart github页面&#xff1a;https://github.com/pyecharts/pyecharts 首先要明确多图叠加到一个图的规则&#xff0c;即多个图只能有一个公共的轴&#xff1a; 比如&#xff0c;横坐标含义相同&#xff08;如时间维度&#xff09;或者&#xff0c;纵坐标取值含义相同 文…

Web3中文|把Web3装进口袋,Solana手机Saga有何魔力?

2月23日&#xff0c;Solana Web3手机Saga发布新的消息&#xff0c;将推出NFT铸造应用程序Minty Fresh。在Minty Fresh&#xff0c;用户仅需轻点并完成拍摄&#xff0c;就可以直接在手机中进行NFT铸造&#xff0c;并在几秒钟内将其转换为链上NFT&#xff0c;NFT还可以发布在 Ins…

STM32学习笔记-SPI

文章目录硬件连接协议层STM32-SPISTM32 SPI框架图SPI初始化结构体SPI 协议是由摩托罗拉公司提出的通讯协议 (Serial Peripheral Interface)&#xff0c;即串行外围设备接口&#xff0c;是一种高速全双工的通信总线。它被广泛地使用在 ADC、LCD 等设备与 MCU 间&#xff0c;要求…

NCRE计算机等级考试Python真题(十一)

第十一套试题1、以下选项对于import保留字描述错误的是&#xff1a;A.import可以用于导入函数库或者库中的函数B.可以使用from jieba import lcut 引入 jieba库C.使用import jieba as jb&#xff0c;引入函数库jieba&#xff0c;取别名jbD.使用import jieba 引入jieba库正确答案…

明明硬件比软件难,但为什么硬件工程师待遇还不如软件?

前言 大家好&#xff0c;最近在知乎上看到一个很有意思的问题&#xff1a; 硬件明明比软件更难&#xff0c;国内的硬件技术也不如软件&#xff0c;为什么硬件工程师待遇还不如软件&#xff1f; 下面分享几位网友的回答&#xff0c;有一定的参考价值&#xff0c;欢迎大家留言讨论…

Dell服务器组Raid + 重装Ubuntu20.0.4

文章目录1. 组建Raid2. 从U盘启动3. 系统安装4. 硬盘分区查看5.后续步骤&#xff1a;1. 组建Raid 1.1. 开机后按CtrlR进入Raid管理界面&#xff1b; 1.2. 选中现有群组后按F2弹出菜单&#xff0c;选择删除现有群组&#xff1b; 1.3. 删除后会列出所有磁盘&#xff0c;仍选…

DSP_TMS320F28377D_ePWM学习笔记

前言 本人需要使用ePWM来控制一个永磁同步电机&#xff08;PMSM&#xff09;, 本文记录了对于TMS320F28377D ePWM模块的学习笔记。主要内容是FOC PMSM控制的ePWM配置&#xff0c;同时包含ADC触发源的配置&#xff0c;关于ADC的学习笔记&#xff0c;请参考DSP_TMS320F28377D_AD…

靶机漏洞那些事儿,这场直播算是讲明白了

CSDN直播间&#xff1a; 小白如何从靶场过渡到实战 ——「业务安全大讲堂第第二季第2期」https://live.csdn.net/room/dingxiangtech/xldogSXD 一名合格的网安工程师&#xff0c;不仅要懂得防漏洞&#xff0c;更要学会找漏洞。 上期直播我们为大家讲解了红队打点与情报收集策…

[busybox] busybox生成一个最精简rootfs(上)

这篇文章是承接着[rootfs]用busybox做一个rootfs(根文件系统)来的&#xff0c;再回看这篇我很久之前写的文章的时候&#xff0c;有一个问题出现在我的脑海中&#xff0c;创建了这个文件那个文件&#xff0c;但确实是每个文件都是必需的吗&#xff1f; 这篇文章我们就来讨论下这…

Graph Neural Network(GNN)图神经网络

Graph Neural Network(GNN)图神经网络&#xff0c;是一种旨在对图结构数据就行操作的深度学习算法。它可以很自然地表示现实世界中的很多问题&#xff0c;包括社交网络&#xff0c;分子结构和交通网络等。GNN旨在处理此类图结构数据&#xff0c;并对图中的节点和边进行预测或执…

PLECS中DLL模块的使用

之前发布了一篇文章&#xff0c;介绍如何使用PSIM中的DLL模块。而本篇文章的内容与之类似&#xff0c;不过主角换成了PLECS。 PLECS和PSIM类似&#xff0c;也属于电力电子仿真软件&#xff0c;使用方便&#xff0c;仿真速度快&#xff0c;和Matlab也有一定的联系&#xff0c;有…