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>

最新文章

  1. How to build a NFS Service
  2. pyqt的信号槽机制(转)
  3. 关于Thread.IsBackground属性的理解(转载)
  4. SMON功能(二):合并空闲区间
  5. ls命令
  6. SSH 使用JUnit测试
  7. R语言笔记
  8. git configuration
  9. Linux 多线程开发
  10. C# dll 事件执行 js 回调函数
  11. 统计学习方法(三)——K近邻法
  12. POJ - 2336 Wireless Network
  13. PageHelper分页插件及通用分页js
  14. 设计模式的uml图的关键(核心)
  15. 常识判断-科技-day123
  16. 京东Alpha平台开发笔记系列(二)
  17. 【Python3练习题 014】 一个数如果恰好等于它的因子之和,这个数就称为“完数”。例如6=1+2+3。编程找出1000以内的所有完数。
  18. Oracle性能优化3-sql优化一定要等价
  19. alpha版发布
  20. cpan安装报错Invalid host name on line 1 at *FirstTime.pm line 1857.

热门文章

  1. Java线程池实现原理及其在美团业务中的实践
  2. 搭建Elasticsearch可视化界面 Kibana
  3. Error Code: 1366. Incorrect DECIMAL value: &#39;0&#39; for column &#39;&#39; at row -1 0.266 sec;
  4. SpringBoot(五):SpringBoot使用拦截器
  5. ngx_http_image_filter_module使用
  6. TCP/IP协议学习-1.概述
  7. springboot的4种属性注入
  8. C语言中字符串详解
  9. JS table排序
  10. CVE-2016-5734-phpmyadmin-4.0.x-4.6.2-代码执行