一、概述
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);
