更新多条记录为多个字段为不同的值
比较普通的写法,是通过循环,依次执行update语句。
Mybatis写法如下:
<update id="updateBatch" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update course
<set>
name=${item.name}
</set>
where id = ${item.id}
</foreach>
</update>
一条记录update一次,性能比较差,容易造成阻塞。
MySQL没有提供直接的方法来实现批量更新,但可以使用case when语法来实现这个功能。
UPDATE user
SET name = CASE id
WHEN 1 THEN '文泽稳'
WHEN 2 THEN '王祺'
END,
age = CASE id
WHEN 1 THEN 26
WHEN 2 THEN 21
END
WHERE id IN (1,2)
这条sql的意思是,如果id为1,则name的值为文泽稳,age的值为26;依此类推。
在Mybatis中的配置则如下:
<update id="updateUsersById" parameterType="com.wenzewen.basic.entity.User">
update user
<trim prefix="set" suffixOverrides=",">
<trim prefix="name =case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="i.name!=null">
when id=#{i.id} then #{i.name}
</if>
</foreach>
</trim>
<trim prefix=" age =case" suffix="end,">
<foreach collection="list" item="i" index="index">
<if test="i.age!=null">
when id=#{i.id} then #{i.age}
</if>
</foreach>
</trim>
</trim>
where
<foreach collection="list" separator="or" item="i" index="index" >
id=#{i.id}
</foreach>
</update>