6. Mybatis resultMap
2024-10-19 06:31:42
resultMap 元素是MyBatis中最重要最强大的元素。它就是让你远离90%的需要从结果集中取出数据的JDBC代码的那东西,而且在一些情形下允许你做一些JDBC不支持的事情。事实上,编写相似于对复杂语句联合映射这些等同的代码,也许可以跨过上千行的代码。ResultMap的设计就是简单语句不需要明确的结果映射,而很多复杂语句确实需要描述它们的关系。
package com.accp.mybatis.model; public class Blog {
private Integer id;
private String title;
private Integer authorId; //省略get和set方法
}
基于JavaBean的规范,上面这个类有3个属性:id,title和authorId。这些在select语句中会精确匹配到列名。
这样的一个JavaBean可以被映射到结果集,就像映射到HashMap一样简单。
<?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.accp.mybatis.model.Blog"> <select id="selectBlog_by_id" parameterType="int" resultType="Blog">
select * from Blog where id = #{id}
</select> </mapper>
这些情况下,MyBatis会在幕后自动创建一个ResultMap,基于属性名来映射列到JavaBean的属性上。如果列名没有精确匹配,你可以在列名上使用select字句的别名(一个标准的SQL特性)来匹配标签。
ResultMap最优秀的地方你已经了解了很多了,但是你还没有真正的看到一个。只是出于示例的原因,让我们来看看最后一个示例中外部的resultMap是什么样子的,这也是解决列名不匹配的另外一种方式。
<resultMap id="Blog_result" type="Blog" >
<id column="id" property="id" />
<result column="title" property="title"/>
<result column="author_id" property="authorId"/>
</resultMap>
引用它的语句使用resultMap属性就行了(注意我们去掉了resultType属性)。比如:
<?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.accp.mybatis.model.Blog"> <resultMap id="Blog_result" type="Blog" >
<id column="id" property="id" />
<result column="title" property="title"/>
<result column="author_id" property="authorId"/>
</resultMap> <!-- resultType与resultMap不能同时使用 -->
<select id="selectBlog_by_id" parameterType="int" resultMap="Blog_result">
select * from Blog where id = #{id}
</select> </mapper>
最新文章
- How to build a NFS Service
- pyqt的信号槽机制(转)
- 关于Thread.IsBackground属性的理解(转载)
- SMON功能(二):合并空闲区间
- ls命令
- SSH 使用JUnit测试
- R语言笔记
- git configuration
- Linux 多线程开发
- C# dll 事件执行 js 回调函数
- 统计学习方法(三)——K近邻法
- POJ - 2336 Wireless Network
- PageHelper分页插件及通用分页js
- 设计模式的uml图的关键(核心)
- 常识判断-科技-day123
- 京东Alpha平台开发笔记系列(二)
- 【Python3练习题 014】 一个数如果恰好等于它的因子之和,这个数就称为“完数”。例如6=1+2+3。编程找出1000以内的所有完数。
- Oracle性能优化3-sql优化一定要等价
- alpha版发布
- cpan安装报错Invalid host name on line 1 at *FirstTime.pm line 1857.
热门文章
- Java线程池实现原理及其在美团业务中的实践
- 搭建Elasticsearch可视化界面 Kibana
- Error Code: 1366. Incorrect DECIMAL value: &#39;0&#39; for column &#39;&#39; at row -1	0.266 sec;
- SpringBoot(五):SpringBoot使用拦截器
- ngx_http_image_filter_module使用
- TCP/IP协议学习-1.概述
- springboot的4种属性注入
- C语言中字符串详解
- JS table排序
- CVE-2016-5734-phpmyadmin-4.0.x-4.6.2-代码执行