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>