批量更新的注意事项

小弟昨日一个需求,就是讲一个list集合 update到一张表中,但与insert的写法不同。需要将list封装成map 在传入xml中进行foreach

<update id="updateYesterdayAmountBatch" parameterType="java.util.Map">
        update debt_current_user_holding_temp dcu set
        dcu.yesterday_amount =
        <foreach collection="tt" item="debtCurrentUserHoldingTemp" index="index" separator=" " open="case id" close="end,">
            when #{debtCurrentUserHoldingTemp.id} then
            #{debtCurrentUserHoldingTemp.yesterdayAmount}
        </foreach>
        dcu.amount =
        <foreach collection="tt" item="debtCurrentUserHoldingTemp" index="index" separator=" " open="case id" close="end,">
            when #{debtCurrentUserHoldingTemp.id} then
            #{debtCurrentUserHoldingTemp.amount}
        </foreach>
        dcu.updated_at =
        <foreach collection="tt" item="debtCurrentUserHoldingTemp" index="index" separator=" " open="case id" close="end">
            when #{debtCurrentUserHoldingTemp.id} then
            #{debtCurrentUserHoldingTemp.updatedAt}
        </foreach>
        where dcu.id in
        <foreach collection="tt" index="index" item="debtCurrentUserHoldingTemp" separator="," open="(" close=")">
            #{debtCurrentUserHoldingTemp.id}
        </foreach>
    </update>

这里要注意,set 后面跟的字段,要将open设置成 case id close = “end”,而where条件要使用in 原因是mybatis在解析时,会将其条件in(1,2,3)等等。而set 后面的字段  会解析成  case id when xx then x when xxx then xxx end,下一个字段,最后一个字段是end  没有逗号。

int updateYesterdayAmountBatch(Map<String, Object> tt);

上述是 mapper中的内容。这样就能实现mybatis的批量更新。原因是mybatis默认会将list类型的参数自动封装成map 并且key= list,vaue 就是集合。可是有时候直接传入list也是可以的。不知道为什么。按照我的写法。如果直接传入list参数 ,会报错,parameter xxx not found。也不知是哪里的问题。后续研究出来接着补充。

insert 使用list作为参数就能直接识别。。为啥update 必须要map呢?待小弟去研究一下mybatis文档再议。

猜你喜欢

转载自my.oschina.net/u/2543341/blog/2252122
今日推荐