Mybatis ResultMap 和 resultType 区别

一、概述
MyBatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap,resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,但是resultType跟resultMap不能同时存在。
在MyBatis进行查询映射时,其实查询出来的每一个属性都是放在一个对应的Map里面的,其中键是属性名,值则是其对应的值。
①当提供的返回类型属性是resultType时,MyBatis会将Map里面的键值对取出赋给resultType所指定的对象对应的属性。所以其实MyBatis的每一个查询映射的返回类型都是ResultMap,只是当提供的返回类型属性是resultType的时候,MyBatis对自动的给把对应的值赋给resultType所指定对象的属性。
②当提供的返回类型是resultMap时,因为Map不能很好表示领域模型,就需要自己再进一步的把它转化为对应的对象,这常常在复杂查询中很有作用。

二、ResultType

Blog.java

  1. public class Blog {  
  2.        private int id;  
  3.        private String title;  
  4.        private String content;  
  5.        private String owner;  
  6.        private List<Comment> comments;  
  7. }  

其所对应的数据库表中存储有id、title、Content、Owner属性。

  1. <typeAlias alias="Blog" type="com.tiantian.mybatis.model.Blog"/>  
  2. <select id="selectBlog" parameterType="int" resultType="Blog">  
  3.       select * from t_blog where id = #{id}  
  4. </select>  


MyBatis会自动创建一个ResultMap对象,然后基于查找出来的属性名进行键值对封装,然后再看到返回类型是Blog对象,再从ResultMap中取出与Blog对象对应的键值对进行赋值。

三、ResultMap
当返回类型直接是一个ResultMap的时候也是非常有用的,这主要用在进行复杂联合查询上,因为进行简单查询是没有什么必要的。先看看一个返回类型为ResultMap的简单查询,再看看复杂查询的用法。

①简单查询的写法

  1. <resultMap type="Blog" id="BlogResult">  
  2.         <id column="id" property="id" />  
  3.         <result column="title" property="title" />  
  4.         <result column="content" property="content" />  
  5.         <result column="owner" property="owner" />  
  6.     </resultMap>  
  7.     <select id="selectBlog" parameterType="int" resultMap="BlogResult">  
  8.         select *  
  9.         from t_blog where id = #{id}  
  10.     </select>  


select映射中resultMap的值是一个外部resultMap的id,表示返回结果映射到哪一个resultMap上,外部resultMap的type属性表示该resultMap的结果是一个什么样的类型,这里是Blog类型,那么MyBatis就会把它当作一个Blog对象取出。resultMap节点的子节点id是用于标识该对象的id的,而result子节点则是用于标识一些简单属性的,其中的Column属性表示从数据库中查询的属性,Property则表示查询出来的属性对应的值赋给实体对象的哪个属性。简单查询的resultMap的写法就是这样的。

猜你喜欢

转载自www.cnblogs.com/zhuyeshen/p/12516594.html