mybatis主查询给子查询传递参数之构造虚拟列

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。之后也就可以将这个值传递给子查询了。

扫描二维码关注公众号,回复: 13147129 查看本文章

猜你喜欢

转载自blog.csdn.net/gongsenlin341/article/details/110955848