Mybatis之ResultMap

news2024/10/6 12:26:40

前言

select语句查询得到的结果集是一张二维表,水平方向上看是一个个字段,垂直方向上看是一条条记录。而Java是面向对象的程序设计语言,对象是根据类定义创建的,类之间的引用关
系可以认为是嵌套的结构。在JDBC编程中,为了将结果集中的数据映射成对象,我们需要自己写代码从结果集中获取数据,然后封装成对应的对象并设置对象之间的关系,而这些都是大量的重复性代码。为了减少这些重复的代码,MyBatis使用<resultMap>节点定义了结果集与结果对象(JavaBean 对象)之间的映射规则,<resultMap>节点可以满足绝大部分的映射需求,从而减少开发人员的重复性劳动,提高开发效率。

ResultMap标签结构

  • constructor - 用于在实例化类时,注入结果到构造方法中
    • idArg - ID 参数;标记出作为 ID 的结果可以帮助提高整体性能
    • arg - 将被注入到构造方法的一个普通结果
  • id – 一个 ID 结果;标记出作为 ID 的结果可以帮助提高整体性能
  • result – 注入到字段或 JavaBean 属性的普通结果
  • association – 一个复杂类型的关联;许多结果将包装成这种类型
    • 嵌套结果映射 – 关联可以是 resultMap 元素,或是对其它结果映射的引用
  • collection – 一个复杂类型的集合
    • 嵌套结果映射 – 集合可以是 resultMap 元素,或是对其它结果映射的引用
  • discriminator – 使用结果值来决定使用哪个 resultMap
    • case – 基于某些值的结果映射
      • 嵌套结果映射 – case 也是一个结果映射,因此具有相同的结构和元素;或者引用其它的结果映射

图示查询结果转为Java对象的过程

假设有这样一个场景:一个博客有一个作者和多条评论。根据博客设置的权限,动态展示阅读数和点赞数。

  • 公开:博客信息 + 阅读数 + 点赞数(PublicBlog)
  • 仅展示阅读数 : 博客信息 + 阅读数(ReadBlog)

如何用ResultMap来描述这种关系
创建mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <properties>
        <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=Asia/Shanghai&amp;allowPublicKeyRetrieval=true"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </properties>

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

    <environments default="default">
        <environment id="default">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/ResultMapMapper.xml" />
    </mappers>

</configuration>
创建ResultMapMapper.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.ys.mybatis.mapper.ResultMapMapper">

    <resultMap id="blogMap" type="com.ys.mybatis.resultmap.Blog">
        <constructor>
            <idArg name="id" column="id"/>
            <arg name="title" column="title"/>
        </constructor>
        <result property="authority" column="authority"/>
        <association property="author">
            <id property="id" column="author_id"/>
            <result property="nickName" column="nick_name"/>
        </association>
        <collection property="comments" ofType="com.ys.mybatis.resultmap.Comment">
            <result property="blogId" column="blog_id"/>
            <result property="content" column="content"/>
        </collection>
        <discriminator javaType="string" column="authority">
            <case value="公开" resultType="com.ys.mybatis.resultmap.PublicBlog">
                <result property="readNum" column="read_num"/>
                <result property="likeNum" column="like_num"/>
            </case>
            <case value="仅显示阅读数" resultType="com.ys.mybatis.resultmap.ReadBlog">
                <result property="readNum" column="read_num"/>
            </case>
        </discriminator>
    </resultMap>   

    <select id="listBlog" resultMap="blogMap">
        select
            b.id,
            b.title,
            a.id as author_id,
            a.nick_name,
            c.blog_id,
            c.content,
            b.read_num,
            b.like_num,
            b.authority
        from blog b
         left join author a on a.id = b.author_id
         left join `comment` c on c.blog_id = b.id
    </select>

</mapper>
创建ResultMapMapper
public interface ResultMapMapper {

    List<Blog> listBlog();
}
创建实体类
@Data
public class Blog {

    private Integer id;

    private String title;

    private Author author;

    private List<Comment> comments;

    private String authority;

    public Blog() {
        System.out.println("调用了空构造方法");
    }

    public Blog(@Param("id") Integer id, @Param("title") String title) {
        System.out.println("调用了两个参数构造方法");
        this.id = id;
        this.title = title;
    }

    @Override
    public String toString() {
        return "Blog{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", author=" + author +
                ", comments=" + comments +
                ", authority='" + authority + '\'' +
                '}';
    }
}

@Data
public class Author {

    private Integer id;

    private String nickName;
}

@Data
public class Comment {

    private Integer id;

    private Integer blogId;

    private String content;

    @Override
    public String toString() {
        return "Comment{" +
                "content='" + content + '\'' +
                '}';
    }
}

@Data
public class PublicBlog extends Blog {

    private Integer readNum;

    private Integer likeNum;

    public PublicBlog() {
    }

    public PublicBlog(@Param("id") Integer id, @Param("title") String title) {
        super(id, title);
    }

    @Override
    public String toString() {
        return "Blog{" +
                "id=" + this.getId() +
                ", title='" + this.getTitle() + '\'' +
                ", author=" + this.getAuthor().toString() +
                ", comments=" + this.getComments() +
                ", authority='" + this.getAuthority() + '\'' +
                ", readNum='" + this.getReadNum() + '\'' +
                ", likeNum='" + this.getLikeNum() + '\'' +
                '}';


    }
}

@Data
public class ReadBlog extends Blog {

    private Integer readNum;

    public ReadBlog() {
    }

    public ReadBlog(@Param("id") Integer id, @Param("title") String title) {
        super(id, title);
    }

    @Override
    public String toString() {
        return "Blog{" +
                "id=" + this.getId() +
                ", title='" + this.getTitle() + '\'' +
                ", author=" + this.getAuthor().toString() +
                ", comments=" + this.getComments() +
                ", authority='" + this.getAuthority() + '\'' +
                ", readNum='" + this.getReadNum() + '\'' +
                '}';
    }
}
创建测试类ResultMapTest 
public class ResultMapTest {

    private SqlSessionFactory sqlSessionFactory;

    @BeforeEach
    public void parse() {
        InputStream inputStream = ConfigurationTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);

    }

    @Test
    public void listBlog() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ResultMapMapper mapper = sqlSession.getMapper(ResultMapMapper.class);
        List<Blog> blogs = mapper.listBlog();
        blogs.forEach(System.out::println);
    }
}

ResultMapMapper.xml 中的 blogMap,通过association标签表示博客和作者一对一的关系,通过collection标签表示博客和评论一对多的关系,通过discriminator标签和authority属性值来动态显示一些数据。

SQL在数据库中的查询结果

 执行测试方法

通过测试结果,我们得出以下结论:

  •  PublicBlog 、ReadBlog 选择了constructor配置的构造方法实例化对象
  • 一共查出来三条数据,根据博客ID分组(分成两组),最后解析成两个Blog对象

源码解析

XMLMapperBuilder#resultMapElement

从上述源码,我们可以得出以下结论:

  • discriminator标签最终会被解析成Discriminator对象
  • 除了discriminator标签以外的其他标签都会被解析成ResultMapping,然后放入一个list中

PS : discriminator标签下有多少个case子标签,就会解析成多少个ResultMap对象

在得到Discriminator对象和ResultMapping集合过后,又结合ResultMap标签的id,type,extends,autoMapping属性构建出一个ResultMapResolver对象,通过其resolve方法,解析出一个ResultMap对象

ResultMap类结构
public class ResultMap {
  private Configuration configuration;

  private String id;
  private Class<?> type;
  private List<ResultMapping> resultMappings;
  private List<ResultMapping> idResultMappings;
  private List<ResultMapping> constructorResultMappings;
  private List<ResultMapping> propertyResultMappings;
  private Set<String> mappedColumns;
  private Set<String> mappedProperties;
  private Discriminator discriminator;
  private boolean hasNestedResultMaps;
  private boolean hasNestedQueries;
  private Boolean autoMapping;
}

其中id,type,resultMappings,discriminator,autoMapping属性都是在构建ResultMapResolver对象的时候,通过构造方法传递过去的,我们不做过多分析

  • idResultMappings :id,idArg标签解析出来的ResultMapping,也会放一份在这个list中,该list用来对查询结果进行分组
  • constructorResultMappings :idArg,arg标签解析出来的ResultMapping,也会放一份在这个list中,该list用来指定构造器实例化对象
  • propertyResultMappings : 非idArg,arg标签解析出来的ResultMapping,也会放一份在这个list中。
  • mappedColumns :ResultMap标签子节点column属性集合
  • mappedProperties :ResultMap标签子节点property属性集合

hasNestedResultMaps,hasNestedQueries我们单独分析

嵌套映射

当hasNestedResultMaps属性为true,我们就称这是一个存在嵌套映射的查询,我们通过源码,分析一下

XMLMapperBuilder#buildResultMappingFromContext

显示指定 : 存在子标签显示指定resultMap。比如ResultMapMapper.xml 中的blogMap,我们可以改成显示指定的形式,明细如下:

<resultMap id="blogMap" type="com.ys.mybatis.resultmap.Blog">
    <constructor>
        <idArg name="id" column="id"/>
        <arg name="title" column="title"/>
    </constructor>
    <result property="authority" column="authority"/>
    <association property="author" resultMap="authorMap"/>
    <collection property="comments" ofType="com.ys.mybatis.parse.Comment" resultMap="commentMap"/>
    <discriminator javaType="string" column="authority">
        <case value="公开" resultMap="publicBlog" resultType="com.ys.mybatis.resultmap.PublicBlog" />
        <case value="仅显示阅读数" resultMap="readBlog" resultType="com.ys.mybatis.resultmap.ReadBlog"/>
    </discriminator>
</resultMap>

 <resultMap id="publicBlog" type="com.ys.mybatis.resultmap.PublicBlog" extends="blogMap">
    <result property="readNum" column="read_num"/>
    <result property="likeNum" column="like_num"/>
 </resultMap>

 <resultMap id="readBlog" type="com.ys.mybatis.resultmap.ReadBlog" extends="blogMap">
    <result property="readNum" column="read_num"/>
 </resultMap>

 <resultMap id="authorMap" type="com.ys.mybatis.resultmap.Author">
    <id property="id" column="author_id"/>
    <result property="nickName" column="nick_name"/>
 </resultMap>

 <resultMap id="commentMap" type="com.ys.mybatis.resultmap.Comment">
    <result property="blogId" column="blog_id"/>
    <result property="content" column="content"/>
 </resultMap>

PS : 如果ResultMap标签中同时存在constructor和discriminator标签,discriminator标签的子标签case必须要指定resultType

隐式构建 :  存在association,collection,case标签,且未配置select属性,Mybatis会隐式构建一个ResultMap对象。测试文件中的blogMap就属于隐式构建

嵌套查询

存在子标签中配置了select属性。比如测试文件中的author属性,我们改成下列形式:

<association property="author" column="author_id" select="getAuthorById"/>
    
<select id="getAuthorById" resultType="com.ys.mybatis.resultmap.Author">
  select id,nick_name from author where id = #{authorId}
</select>
延迟加载

在嵌套查询的基础上,开启延迟加载的两种方式

1. 在mybatis-config.xml中添加配置

<setting name="lazyLoadingEnabled" value="true"/>

2.在association、collection等标签中配置fetchType属性,举例如下:

<association property="author" column="author_id" select="getAuthorById" fetchType="lazy"/>

PS : fetchType优先级高于全局配置lazyLoadingEnabled

延迟加载在mybatis中的应用

DefaultResultSetHandler#createResultObject

如果存在嵌套查询,且属性是懒加载的,则进行动态代理。详情请移步相关博客:Mybatis懒加载

extends

MapperBuilderAssistant#addMap

  • 子map中配置的对象关系映射会覆盖父map中配置的对象关系映射
  • 子map中配置的对象实例化方式会覆盖父map中配置的对象实例化方式
autoMapping
  • 属性值为 true :  嵌套和非嵌套的情况下,都会自动映射
  • 属性值为 false : autoMappingBehavior属性值控制其自动映射行为
    • NONE:表示关闭自动映射
    • PARTIAL:只会自动映射没有定义嵌套结果映射的字段 (默认值)
    • FULL:会自动映射任何复杂的结果集(无论是否嵌套)
修改autoMappingBehavior属性默认值
<setting name="autoMappingBehavior" value="NONE"/>

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

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

相关文章

政务服务电子文件归档和电子档案管理系统,帮助组织收、管、存、用一体化

作为数字政府建设的重要抓手&#xff0c;政务服务改革经过多年发展&#xff0c;截至 2022 年底&#xff0c;全国一体化在线政务服务平台实名用户超过10亿人&#xff0c;在政务服务、办件过程中出现了大量需要归档的电子文件&#xff0c;对于电子档案、电子证照的需求愈加强烈。…

Sql Server 2016数据库定时备份

一、 配置备份计划任务 选中“维护计划“--右键--“维护计划向导” 完成

2024 年 数维杯(C题)大学生数学建模挑战赛 | 天然气水合物资源 | 数学建模完整代码+建模过程全解全析

当大家面临着复杂的数学建模问题时&#xff0c;你是否曾经感到茫然无措&#xff1f;作为2022年美国大学生数学建模比赛的O奖得主&#xff0c;我为大家提供了一套优秀的解题思路&#xff0c;让你轻松应对各种难题。 CS团队倾注了大量时间和心血&#xff0c;深入挖掘解决方案。通…

1.python爬虫爬取视频网站的视频可下载的源url

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 一、爬取的源网站二、爬取过程详解1.首先我们需要解析网站的源码&#xff0c;按F12&#xff0c;在Elements下查看网站的源码2.获取视频的页数3.获取每一页所哟视频的…

基于FPGA实现的HDMI TO MIPI扩展显示器方案

FPGA方案&#xff0c;HDMI IN接收原始HDMI 信号&#xff0c;输出显示到LCD 屏上 客户应用&#xff1a;扩展显示器 主要特性&#xff1a; 1.支持2K以下任意分辨率显示 2.支持OSD 叠加多个图层 3.支持MIPI/EDP/LVDS/RGB屏 4.支持放大缩小匹配屏分辨率 5.零延时&#xff0c;输…

从零学算法42

42.接雨水 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图&#xff0c;计算按此排列的柱子&#xff0c;下雨之后能接多少雨水。 示例 1&#xff1a; 输入&#xff1a;height [0,1,0,2,1,0,1,3,2,1,2,1] 输出&#xff1a;6 解释&#xff1a;上面是由数组 [0,1,0,2,1,0,1,3…

蚂蚁面试:DDD外部接口调用,应该放在哪一层?

尼恩说在前面&#xff1a; 在40岁老架构师 尼恩的读者交流群(50)中&#xff0c;最近有小伙伴拿到了一线互联网企业如字节、阿里、滴滴、极兔、有赞、希音、百度、网易、美团的面试资格&#xff0c;遇到很多很重要的面试题&#xff1a; DDD 的外部接口调用&#xff0c;应该放在…

Java方法和数组

方法 Java中的方法就是c语言中的函数。 方法的定义 定义格式如下 修饰符 返回值 方法名([参数列表]){代码块[return 返回值;] } //方括号[]括起来代表可以没有&#xff0c;不是必须有的方法名采用小驼峰命名&#xff08;就是有多个单词&#xff0c;第一个单词首字母小写其…

阅读送书抽奖?玩转抽奖游戏,js-tool-big-box工具库新上抽奖功能

先讨论一个问题&#xff0c;你做软件工作是为了什么&#xff1f;从高中选专业&#xff0c;就喜欢上了软件开发&#xff1f;还是当初毕业不知道干啥&#xff0c;不喜欢自己的专业&#xff0c;投入软件开发的怀抱&#xff1f;还是干着干着别的&#xff0c;突然觉得互联网行业真不…

前端技术交流群

欢迎来到前端筱园用户交流&#xff01;这是一个专注于前端编程技术、学习资源和行业动态的讨论平台。在这里&#xff0c;你可以分享经验、提问、回答问题&#xff0c;与其他前端开发者一起学习和成长。 &#x1f31f;亲爱的朋友们&#x1f31f; 大家好&#xff01;感谢你们一直…

《Tam》论文笔记(下)

3 Method 3.1. The Overview of Temporal Adaptive Module 正如我们在第1节中讨论的&#xff0c;视频数据通常表现出由相机运动和速度变化等因素引起的复杂时间动态。因此&#xff0c;我们的目标是通过引入具有视频特定内核的时间自适应模块 (TAM) 来解决这个问题&#xff0c…

一键自动化博客发布工具,用过的人都说好(infoq篇)

infoq的博客发布界面也是非常简洁的。首页就只有基本的标题&#xff0c;内容和封面图片&#xff0c;所以infoq的实现也相对比较简单。 一起来看看吧。 前提条件 前提条件当然是先下载 blog-auto-publishing-tools这个博客自动发布工具,地址如下&#xff1a;https://github.c…

营收如泡沫,利润如刀片,万辰集团万店梦想下的阴影

&#xff08;作者注&#xff1a;本文建议配乐《泡沫》阅读&#xff01;&#xff09; 从“食用菌第一股”转型为“量贩零食第一股”的首个财年&#xff0c;万辰集团新业务发展迅猛。 财报显示&#xff0c;2023年公司量贩零食业务实现营业收入87.59亿元&#xff0c;同比增长1305…

微火全域运营平台的优缺点分别是什么?

随着全域运营赛道的兴起&#xff0c;微火全域运营平台在市场占有率持续走高&#xff0c;与之相关的各类问题也层出不穷。其中&#xff0c;微火全域运营平台是什么、微火全域运营平台的优缺点等与平台本身相关的问题长期位居话题榜前列。 所谓微火全域运营平台&#xff0c;就是由…

京东手势验证码-YOLO姿态识别+Bézier curve轨迹拟合

这次给老铁们带来的是京东手势验证码的识别。 目标网站&#xff1a;https://plogin.m.jd.com/mreg/index 验证码如下图: 当第一眼看到这个验证码的时候&#xff0c;就头大了&#xff0c;这玩意咋识别&#xff1f;&#xff1f;&#xff1f; 静下心来细想后的一个方案&#xf…

使用apache和htaccess对目录访问设置密码保护配置教程

对目录设置密码保护配置说明 我们有时候访问某些网站的时候&#xff0c;要求输入用户名和密码才能访问。这是为了保护隐私&#xff0c;只让经过许可的人访问。 在本教程中主要介绍两种方法&#xff0c;一种是通过apache httpd.conf配置文件对管理后台目录设置密码保护&#xff…

ESP32引脚入门指南(四):从理论到实践(PWM)

引言 ESP32 作为物联网领域的明星微控制器&#xff0c;除了强大的Wi-Fi和蓝牙功能&#xff0c;还内置了丰富的外设资源&#xff0c;其中就包括高级的PWM&#xff08;脉冲宽度调制&#xff09;功能。本文将深入探讨ESP32的PWM引脚&#xff0c;解析其工作原理&#xff0c;并通过…

分布式与一致性协议之Quorum NWR算法

Quorum NWR算法 概述 不知道你在工作中有没有遇到过这样的事情:你开发实现了一套AP型分布式系统&#xff0c;实现了最终一致性&#xff0c;且业务接入后运行正常&#xff0c;一切看起来都那么美好。 可是突然有同事说&#xff0c;我们要拉这几个业务的数据做实时分析&#xf…

进口原装二手 Keysight86142B 是德86142A 高性能光谱分析仪

进口原装二手 Keysight86142B 是德86142A 高性能光谱分析仪 内置测试应用程序 • 10 pm 波长精度 • 快速双扫法 • 覆盖 S、C 和 L 波段 Keysight 86142B是一款台式光谱分析仪&#xff08;OSA&#xff09;&#xff0c;最适于对功率和波长精度、动态范围和低偏振敏感性都要…

asp.net论坛指南系统

说明文档 运行前附加数据库.mdf&#xff08;或sql生成数据库&#xff09; 主要技术&#xff1a; 基于asp.net架构和sql server数据库 登陆可查看 浏览记录 TA的发布 TA的回复 TA的收藏 TA的点赞 管理员登陆可以查看举报管理 编辑管理 认证审核 帖子置顶申请审核 运行环境…