Update a single record
UPDATE course SET name = ‘course1‘ WHERE id = ‘id1‘;
Update the same field of multiple records to the same value.
UPDATE course SET name = ‘course1‘ WHERE id in (‘id1‘, ‘id2‘, ‘id3);
Update multiple records with different values for multiple fields
The general statement is to execute the update statement in sequence through a loop.
Mybatis is written as follows:
<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>
A record is updated once, which has poor performance and may cause blocking.
MySQL does not provide a direct method for batch update, but you can use the case when syntax to implement this function.
UPDATE course 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‘ ENDWHERE id IN (1,2,3)
This SQL statement indicates that if ID is 1, the value of name is name1, and the value of title is new title1.
The configuration in mybatis is as follows:
<update id="updateBatch" parameterType="list"> update course <trim prefix="set" suffixOverrides=","> <trim prefix="peopleId =case" suffix="end,"> <foreach collection="list" item="i" index="index"> <if test="i.peopleId!=null"> when id=#{i.id} then #{i.peopleId} </if> </foreach> </trim> <trim prefix=" roadgridid =case" suffix="end,"> <foreach collection="list" item="i" index="index"> <if test="i.roadgridid!=null"> when id=#{i.id} then #{i.roadgridid} </if> </foreach> </trim> <trim prefix="type =case" suffix="end," > <foreach collection="list" item="i" index="index"> <if test="i.type!=null"> when id=#{i.id} then #{i.type} </if> </foreach> </trim> <trim prefix="unitsid =case" suffix="end," > <foreach collection="list" item="i" index="index"> <if test="i.unitsid!=null"> when id=#{i.id} then #{i.unitsid} </if> </foreach> </trim> </trim> where <foreach collection="list" separator="or" item="i" index="index" > id=#{i.id} </foreach></update>
Batch update of mybatis