您的位置:首页 > 编程语言

Mybatis映射中的resultType和resultMap之代码详解

2017-09-23 18:24 453 查看
一、概述

MyBatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap,resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,但是resultType跟resultMap不能同时存在。

在MyBatis进行查询映射时,其实查询出来的每一个属性都是放在一个对应的Map里面的,其中键是属性名,值则是其对应的值。

①当提供的返回类型属性是resultType时,MyBatis会将Map里面的键值对取出赋给resultType所指定的对象对应的属性。所以其实MyBatis的每一个查询映射的返回类型都是ResultMap,只是当提供的返回类型属性是resultType的时候,MyBatis对自动的给把对应的值赋给resultType所指定对象的属性。

②当提供的返回类型是resultMap时,因为Map不能很好表示领域模型,就需要自己再进一步的把它转化为对应的对象,这常常在复杂查询中很有作用。

二、ResultType

a.返回实体
SQL:
<select id="getCollectionProduct2" resultType="com.alqsoft.entity.collectionproduct.CollectionProduct">
SELECT * FROM
alq_collection_product
where member_id = #{mid,jdbcType=BIGINT} and product_id = #{pid,jdbcType=BIGINT}
</select>
对应的dao接口是:
CollectionProduct getCollectionProduct2(@Param("mid") Long id, @Param("pid") Long pid);

b.返回java.util.Map
SQL:
<select id="getCollectionProductList" resultType="java.util.Map">
SELECT cp.id,p.id productId,p.name,p.imageurl,h.id hunterId,p.status productStatus,
(SELECT ROUND(ps.sale_price/100,2) FROM alq_product_specification ps
WHERE ps.product_id= p.id and ifnull(ps.is_delete,0)=0 ORDER BY ps.created_time ASC LIMIT 1 ) price FROM
alq_product p ,alq_collection_product cp,alq_hunter h WHERE p.id=cp.product_id AND h.id=p.hunter_id AND cp.type= 0
AND cp.member_id = #{uid,jdbcType=BIGINT}
LIMIT  #{page} , #{rows}
</select>

对应的dao接口是:

List<Map<String,Object>> getCollectionProductList(Map<String,Object> map);

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


<resultMap id="BaseResultMap" type="com.alqsoft.vo.CollectionProductVO" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="type" property="type" jdbcType="INTEGER" />
<result column="member_id" property="memberId" jdbcType="BIGINT" />
<result column="product_id" property="productId" jdbcType="BIGINT"/>
</resultMap>

<sql id="Base_Column_List" >
id,  type, member_id,product_id
</sql>

<select id="getCollectionProduct" resultMap="BaseResultMap" >
select
<include refid="Base_Column_List" />

from alq_collection_product
where member_id = #{mid,jdbcType=BIGINT} and product_id = #{pid,jdbcType=BIGINT}
</select>

对应的dao接口是:

CollectionProductVO getCollectionProduct(@Param("mid") Long id, @Param("pid") Long pid);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: