当前位置:首页>编程日记>正文

Mybatis 强大的结果映射器ResultMap

1. 前言

resultMap 元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets 数据提取代码中解放出来,并在一些情形下允许你进行一些 JDBC 不支持的操作。实际上,在为一些比如连接的复杂语句编写映射代码的时候,一份 resultMap 能够代替实现同等功能的数千行代码。ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。

resultMap 可以将查询到的复杂数据,比如多张表的数据、一对一映射、一对多映射等复杂关系聚合到一个结果集当中。日常的业务开发通常都会和它打交道,今天就对 resultMap 进行一个详细讲解。文末有 DEMO

2. resultMap

接下来我们来看看 resultMap 是如何进行映射的。

2.1 Getter/Setter 注入

我们声明一个数据库对应的实体类:

/*** @author felord.cn* @since 16:50**/
@Data
public class Employee implements Serializable {private static final long serialVersionUID = -7145891282327539285L;private String employeeId;private String employeeName;private Integer employeeType;
}

那么它对应的 resultMap 为:

<mapper namespace="cn.felord.mybatis.mapper.EmployeeMapper"><resultMap id="EmployeeMap" type="cn.felord.mybatis.entity.Employee"><id column="employee_id" property="employeeId"/><result column="employee_name" property="employeeName"/><result column="employee_type" property="employeeType"/></resultMap>
</mapper>

我们来解释这些配置的属性:

<mapper namespace="全局唯一的名称空间"><resultMap id="本namespace下唯一" type="对应映射的实体"><id column="数据库主键字段名或者别名,使用它提高整体性能" property="对应实体属性"/><result column="数据库字段名或者别名" property="对应实体属性"/></resultMap>
</mapper>

以上方式是通过 Getter 和 Setter 方法进行注入,也就是实体类必须有无参构造,对应属性必须有Getter 和 Setter 方法。

2.2 构造注入

Getter 和 Setter 方法进行注入是我们最常用的方式。但是 Mybatis 同样支持构造注入,如果 Employee 存在如下构造方法:

public Employee(String employeeId, String employeeName, Integer employeeType) {this.employeeId = employeeId;this.employeeName = employeeName;this.employeeType = employeeType;
}

那么对应的 resultMap 可以这样写:

<mapper namespace="cn.felord.mybatis.mapper.EmployeeMapper"><resultMap id="EmployeeMap" type="cn.felord.mybatis.entity.Employee"><constructor><idArg column="employee_id" javaType="String"/><arg column="employee_name" javaType="String"/><arg column="employee_type" javaType="String"/></constructor></resultMap>
</mapper>

细心的同学发现这里并没有 property 属性,其实当你不声明property 属性时会按照构造方法的参数列表顺序进行注入。

在 Mybatis 3.4.3 引入了 name 属性后我们就可以打乱 constructor 标签内的 arg 元素的顺序了。

<mapper namespace="cn.felord.mybatis.mapper.EmployeeMapper"><resultMap id="EmployeeConstructorMap" type="cn.felord.mybatis.entity.Employee"><constructor><idArg column="employee_id" javaType="String" name="employeeId"/><!-- 你可以不按参数列表顺序添加--><arg column="employee_type" javaType="Integer" name="employeeType"/><arg column="employee_name" javaType="String" name="employeeName"/></constructor></resultMap>
</mapper>

2.3 继承关系

像 Java 中的类一样,resultMap 也是可以继承的。下面是两个有继承关系的 Java 类:

那么 RegularEmployee 的 resultMap 就可以这么写:

<resultMap id="RegularEmployeeMap" extends="EmployeeMap" type="cn.felord.mybatis.entity.RegularEmployee"><result column="level" property="level"/><result column="job_number" property="jobNumber"/><association property="department" javaType="cn.felord.mybatis.entity.Department"><id column="department_id" property="departmentId"/><result column="department_name" property="departmentName"/><result column="department_level" property="departmentLevel"/></association>
</resultMap>

跟 Java 的继承关键字一样使用 extends 来进行继承。

2.4 一对一关联

明眼人会看出来 2.3 最后一个 resultMap 示例中有一个 association 标签。这个用来做什么用呢?打个比方,每一个正式员工 RegularEmployee会对应一个部门 Department,业务中会有把这种 一对一 关系查询出来的需求。所以 association 就派上了用场。

<resultMap id="RegularEmployeeMap" extends="EmployeeMap" type="cn.felord.mybatis.entity.RegularEmployee"><result column="level" property="level"/><result column="job_number" property="jobNumber"/><association property="属性名称" javaType="对应的Java类型"><id column="department_id" property="departmentId"/><result column="department_name" property="departmentName"/><result column="department_level" property="departmentLevel"/></association>
</resultMap>

association 可以继续嵌套下去,有可能关联的对象中还有一对一关系。

2.5 一对多关联

有一对一关联,自然会有一对多关联。我们反客为主,一个部门有多个员工,我们可能需要查询一个部门的信息以及所有员工的信息装载到 DepartmentAndEmployeeList中去。

/*** @author felord.cn* @since 15:33**/
public class DepartmentAndEmployeeList extends Department {private static final long serialVersionUID = -2503893191396554581L;private List<Employee> employees;public List<Employee> getEmployees() {return employees;}public void setEmployees(List<Employee> employees) {this.employees = employees;}
}

我们可以在 resultMap 中使用 collection 关键字来处理一对多映射关系:

<resultMap id="DepartmentAndEmployeeListMap" extends="DepartmentMap"type="cn.felord.mybatis.entity.DepartmentAndEmployeeList"><collection property="employees" ofType="cn.felord.mybatis.entity.RegularEmployee"><id column="employee_id" property="employeeId"/><result column="employee_name" property="employeeName"/><result column="level" property="level"/><result column="job_number" property="jobNumber"/></collection>
</resultMap>

2.6 鉴别器

大家都知道,员工并不都是正式工,还有临时工。有时候我们也期望能够将这两种区分开来,至于原因你懂的。不深入讨论这个问题了。就这个需求而言我们的映射关系又复杂了,我们需要根据某个条件来判断哪条数据是正式工,哪条数据是临时工,然后分别装入下面这个实体类的 regularEmployeestemporaryEmployees中。

/*** @author felord.cn* @since 15:33**/
public class DepartmentAndTypeEmployees extends Department {private static final long serialVersionUID = -2503893191396554581L;private List<RegularEmployee> regularEmployees;private List<TemporaryEmployee> temporaryEmployees;// getter setter
}

鉴别器(discriminator)元素就是被设计来应对这种情况的,另外也能处理其它情况,例如类的继承层次结构。鉴别器的概念很好理解——它很像 Java 语言中的 switch 语句。

为此我们需要在 Employee 类中增加一个 int类型的 employeeType属性来区分正式工和临时工,其中 1代表正式工,而 0代表临时工。然后我们来编写查询 DepartmentAndTypeEmployees 的 resultMap :

<resultMap id="DepartmentAndTypeEmployeesMap" extends="DepartmentMap"type="cn.felord.mybatis.entity.DepartmentAndTypeEmployees"><collection property="regularEmployees" ofType="cn.felord.mybatis.entity.RegularEmployee"><discriminator javaType="int" column="employee_type"><case value="1"><id column="employee_id" property="employeeId"/><result column="employee_name" property="employeeName"/><result column="employee_type" property="employeeType"/><result column="level" property="level"/><result column="job_number" property="jobNumber"/></case></discriminator></collection><collection property="temporaryEmployees" ofType="cn.felord.mybatis.entity.TemporaryEmployee"><discriminator javaType="int" column="employee_type"><case value="0"><id column="employee_id" property="employeeId"/><result column="employee_name" property="employeeName"/><result column="employee_type" property="employeeType"/><result column="company_no" property="companyNo"/></case></discriminator></collection>
</resultMap>

切记一定是先声明 DepartmentAndTypeEmployees的两个 List ,然后在 collection 标签内部使用 discriminator 标签。

这里很容易犯以下错误,下面的写法满足不了上述需求的

<resultMap id="DepartmentAndTypeEmployeesMap" extends="DepartmentMap"type="cn.felord.mybatis.entity.DepartmentAndTypeEmployees"><discriminator javaType="int" column="employee_type"><case value="1"><collection property="regularEmployees" ofType="cn.felord.mybatis.entity.RegularEmployee"><!--省略--></collection></case><case value="0"><collection property="temporaryEmployees" ofType="cn.felord.mybatis.entity.TemporaryEmployee"><!--省略--></collection></case></discriminator></resultMap>

这种写法的意思是:当发现该条数据中 employee_type=1 时,就新建一个 List<RegularEmployee> 并把该条数据放进去,每次都会新建一个 List<RegularEmployee> ;当employee_type=0 时也一样。这样的话就会返回一个 List<DepartmentAndTypeEmployees> 。

3. 总结

resultMap 能够满足大部分业务场景对于数据映射的需求,今天我们对 Mybatis 中 resultMap 的一些用法进行了讲解,其实 resultMap 还有一些有用的属性,基于篇幅的原因这里不再讲解,可阅读 Mybatis 官方文档。但是请注意虽然 resultMap 功能强大,一定要合理使用,级联过于复杂会影响后期维护和性能。比如当一对多映射时,多的一方如果数据条数过大,会增加内存消耗和读写性能。希望今天的文章对你使用 resultMap 有所帮助,更及时的技术资讯请多多关注:码农小胖哥

往期推荐

面试:那些问哭你的Redis分布式锁!

HTTP/3 来了 !HTTP/2 还没怎么用起来呢,先一起扫个盲吧!

Nacos 1.3.0 发布,一个修炼内功的版本:全新内核构建!

疯抢当当图书 618 优惠码,花 120 买 300

万字超强图文讲解 AQS 以及 ReentrantLock 应用

架构师究竟要不要写代码?

面试:String 五连杀 !你还满血吗 ?

本文章的 DEMO ,可关注下方公众号,回复 resultMap 获取。


http://www.coolblog.cn/news/2874b160d04dabfb.html

相关文章:

  • asp多表查询并显示_SpringBoot系列(五):SpringBoot整合Mybatis实现多表关联查询
  • s7day2学习记录
  • 【求锤得锤的故事】Redis锁从面试连环炮聊到神仙打架。
  • 矿Spring入门Demo
  • 拼音怎么写_老师:不会写的字用圈代替,看到孩子试卷,网友:人才
  • Linux 实时流量监测(iptraf中文图解)
  • Win10 + Python + GPU版MXNet + VS2015 + RTools + R配置
  • 美颜
  • shell访问php文件夹,Shell获取某目录下所有文件夹的名称
  • 如何优雅的实现 Spring Boot 接口参数加密解密?
  • LeCun亲授的深度学习入门课:从飞行器的发明到卷积神经网络
  • Mac原生Terminal快速登录ssh
  • java受保护的数据与_Javascript类定义语法,私有成员、受保护成员、静态成员等介绍...
  • mysql commit 机制_1024MySQL事物提交机制
  • 支撑微博千亿调用的轻量级RPC框架:Motan
  • jquery 使用小技巧
  • 2019-9
  • 法拉利虚拟学院2010 服务器,法拉利虚拟学院2010
  • vscode pylint 错误_将实际未错误的py库添加到pylint白名单
  • 科学计算工具NumPy(3):ndarray的元素处理
  • 工程师在工作电脑存 64G 不雅文件,被公司开除后索赔 41 万,结果…
  • linux批量创建用户和密码
  • newinsets用法java_Java XYPlot.setInsets方法代碼示例
  • js常用阻止冒泡事件
  • 气泡图在开源监控工具中的应用效果
  • 各类型土地利用图例_划重点!国土空间总体规划——土地利用
  • php 启动服务器监听
  • dubbo简单示例
  • 【设计模式】 模式PK:策略模式VS状态模式
  • [iptables]Redhat 7.2下使用iptables实现NAT
  • Ubuntu13.10:[3]如何开启SSH SERVER服务
  • CSS小技巧——CSS滚动条美化
  • JS实现-页面数据无限加载
  • 阿里巴巴分布式服务框架 Dubbo
  • 最新DOS大全
  • Django View(视图系统)
  • 阿里大鱼.net core 发送短信
  • 程序员入错行怎么办?
  • 两张超级大表join优化
  • 第九天函数
  • Linux软件安装-----apache安装
  • HDU 5988 最小费用流
  • Sorenson Capital:值得投资的 5 种 AI 技术
  • 《看透springmvc源码分析与实践》读书笔记一
  • 正式开课!如何学习相机模型与标定?(单目+双目+鱼眼+深度相机)
  • Arm芯片的新革命在缓缓上演
  • nagios自写插件—check_file
  • python3 错误 Max retries exceeded with url 解决方法
  • 行为模式之Template Method模式
  • 通过Spark进行ALS离线和Stream实时推荐