1 更新单条记录
UPDATE course SET name = 'course1' WHEREid = 'id1';
2 更新多条记录的同一个字段为同一个值
UPDATE course SET name = 'course1' WHERE id in ('id1','id2','id3);
3 更新多条记录为多个字段为不同的值
3.1 比较普通的写法,是通过循环,依次执行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一次,性能比较差,容易造成阻塞。
需要注意:数据连接需要加一个允许批量执行的配置 &allowMultiQueries=true
3.2 case when 语法来实现
<update id="updateBatch" parameterType="java.util.List">
update mydata_table
<trim prefix="set" suffixOverrides=",">
<trim prefix="status =case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.status !=null and item.status != -1">
when id=#{item.id} then #{item.status}
</if>
<if test="item.status == null or item.status == -1">
when id=#{item.id} then mydata_table.status//原数据
</if>
</foreach>
</trim>
</trim>
where id in
<foreach collection="list" index="index" item="item" separator="," open="(" close=")">
#{item.id,jdbcType=BIGINT}
</foreach>
</update>
<trim>属性说明
- 1.prefix,suffix:表示在trim标签包裹的部分的前面或者后面添加内容
- 2.如果同时有prefixOverrides,suffixOverrides 表示会用prefix,suffix覆盖Overrides中的内容。
- 3.如果只有prefixOverrides,suffixOverrides 表示删除开头的或结尾的xxxOverides指定的内容。