0
点赞
收藏
分享

微信扫一扫

mybatis批量更新数据SQL


Mybatis的XML写法如下: 

<update id="updateList"  parameterType="java.util.List">  
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update tab
<set>
name=${item.name}
</set>
where id = ${item.id}
</foreach>
</update>

一条记录update一次,性能比较差,容易造成阻塞。

MySQL没有提供直接的方法来实现批量更新,但可以使用case when语法来实现这个功能。

UPDATE tab
SET name = CASE id
WHEN 1 THEN 'name1'
WHEN 2 THEN 'name2'
WHEN 3 THEN 'name3'
END,
title = CASE id
WHEN 1 THEN 'New Title 1'
WHEN 2 THEN 'New Title 2'
WHEN 3 THEN 'New Title 3'
END
WHERE id IN (1,2,3)

这条sql的意思是,如果id为1,则name的值为name1,title的值为New Title1;依此类推。

所以在Mybatis中这么写

update tab
set name =
<foreach collection="list" item="item" index="index"
separator=" " open="case" close="end,">
when id = #{item.id} then #{item.name}
</foreach>

where id in
<foreach collection="list" index="index" item="item" separator="," open="(" close=")">
#{item.id}
</foreach>

 

举报

相关推荐

0 条评论