1. 程式人生 > 其它 >mybatis主查詢給子查詢傳遞引數之構造虛擬列

mybatis主查詢給子查詢傳遞引數之構造虛擬列

技術標籤:# 開發中遇到的坑mybatisjavamysql

1.概述

今天做專案遇到了一個情況,在主查詢中的結果當中,不存在子查詢需要的條件引數的情況下,無法將程式碼中傳入的引數傳遞給子查詢。

例如下面的程式碼

在這裡插入圖片描述

selectAll對應的程式碼如下:

		<sql id="vipViceColumns">
    		vip_id,name,gender,birthday,tel,is_vip,avatar
		</sql>
		<select id="selectAll" resultMap="vipVice"
>
select <include refid="vipViceColumns"></include> from Vip </select> <resultMap id="vipVice" type="hdu.gongsenlin.demo.entity.VO.VipVice"> <collection property="cardViceVOs" ofType="hdu.gongsenlin.demo.entity.VO.CardViceVO"
column="{vipId = vip_id,storeId = store_id}" select="hdu.gongsenlin.demo.dao.CardViceMapper.selectByStoreIdAndVipId" fetchType="eager">
</collection> </resultMap>

上面的主查詢是selectAll,得到的結果欄位如vipViceColumns所示。

執行完主查詢之後,結果集對映時發現有子查詢,會進行子查詢的邏輯。

眾所周知,collection標籤當中的column欄位可以傳遞子查詢需要的引數。

但條件是這些欄位需要出現在主查詢的結果當中,此時問題來了!storeId並不在主查詢的結果當中,無法將storeId傳入到子查詢。

所以就有了虛擬列

用法如下:

<sql id="vipViceColumns">
    vip_id,name,gender,birthday,tel,is_vip,avatar,
    case when (${storeId} IS NULL) then NULL else ${storeId} end as store_id
</sql>

通俗的講就是構造一個列,拼接在主查詢的查詢結果的後面。列中的內容,也就是在Service中呼叫mapper時傳入的引數,這樣主查詢的結果當中自然就有了storeId。之後也就可以將這個值傳遞給子查詢了。