mybatis获取map中的key和value

方式一:

dao接口

int updateByBatch(@Param("content") Map<String, Integer> alreadySoldNumMap);

mapper

<update id="updateByBatch" parameterType="java.util.Map">  
        update COUPON_CATEGORY  
        <trim prefix="set" suffixOverrides=",">  
              
            <trim prefix="ALREADY_SOLD_NUM = case" suffix="end,">  
               <foreach collection="content.keys" item="key" index="index">  
                     when ID=#{key} then ALREADY_SOLD_NUM+#{content[${key}]}  
                </foreach>
            </trim>  
              
        </trim>  
        where  
<!-- 循环key  -->
        <foreach collection="content.keys" separator="or" item="key" index="index">  
            ID=#{key}  
        </foreach>  
    </update>

这种方式#{content[KaTeX parse error: Can't use function '\]' in math mode at position 6: {key}\̲]̲}获取map中的value,传…{key}]}还可以写成${content[key]}方式。

<!-- 循环value  -->
<foreach collection="content.values" separator="or" item="value" index="index">  
     ALREADY_SOLD_NUM=#{value}  
</foreach> 

方式二:如果传入的map的key要适用所有类型,可以使用下面的方式

遍历Map中的entrySet,然后把key扔进index里面,value扔进item中。

例如:dao接口,map的key用Long类型

int updateByBatch(@Param("content") Map<Long, Integer> alreadySoldNumMap);

mapper

<update id="updateByBatch" parameterType="java.util.Map">  
        update COUPON_CATEGORY  
        <trim prefix="set" suffixOverrides=",">  
              
            <trim prefix="ALREADY_SOLD_NUM = case" suffix="end,">  
               <foreach collection="content.entrySet()" item="value" index="key">  
                     when ID=#{key} then ALREADY_SOLD_NUM+#{value}  
                </foreach>
            </trim>  
              
        </trim>  
        where  
        <foreach collection="content.keys" separator="or" item="key" index="index">  
            ID=#{key}  
        </foreach>  
    </update>

参考博客: http://blog.csdn.net/clementad/article/details/55099432

另附:

在解决此问题的过程当中,使用的是测试类,可以就是在console中打印不出sql语句来。参考了这篇文章《mybatis结合log4j打印SQL日志》,找到了sql语句。

小编使用的方法是直接调试出sql语句。SimpleExecutor.class在mybatis.jar包里面。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值