小弟昨日一个需求,就是讲一个list集合 update到一张表中,但与insert的写法不一样。须要将list封装成map 在传入xml中进行foreachjava
<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 没有逗号。mybatis
int updateYesterdayAmountBatch(Map<String, Object> tt);
上述是 mapper中的内容。这样就能实现mybatis的批量更新。缘由是mybatis默认会将list类型的参数自动封装成map 而且key= list,vaue 就是集合。但是有时候直接传入list也是能够的。不知道为何。按照个人写法。若是直接传入list参数 ,会报错,parameter xxx not found。也不知是哪里的问题。后续研究出来接着补充。app
insert 使用list做为参数就能直接识别。。为啥update 必需要map呢?待小弟去研究一下mybatis文档再议。code