批量修改sql语句
1.批量修改方式一:(此种方式适用于针对每条的修改值都不同)
注意的是 separator是用“;” 分号分割的。这个sql语句输出来后是如下的形式:
update table set col1 = ?,col2 = ? where id =? ;update table set col1 = ?, set col2 = ? where id = ?
<foreach item="item" index="index" collection="list" separator=";">
UPDATE table
<set>
column1 = #{item.val1},
column2 = #{item.val2}
</set>
<where>
id = #{item.id}
</where>
</foreach>
2.批量修改方式二:(此种方式适用于根据一个列的唯一标识修改相同的数据比如给表中添加默认值等操作)
这里separator使用“,”分割。这个sql语句输出控制台的形式如下(这里的open和close省去了):
update table set column1 = ? ,column2 = ? where id in (?,?,?,?)
update table set column1 = #{val1},column2 = #{val2} where id in
<foreach item="item" index="index" collection="list" separator=",">
id = #{item.id}
</foreach>
3.批量插入方式:
这个sql语句输出后的形式如下:
insert into table (c1,c2,c3,c4) values(?,?,?,?),(?,?,?,?)
insert into table (col1,col2,col3,col4) values
<foreach item="item" index="index" collection="list" separator=",">
(#{item.val1},#{item.val2},#{item.val3},#{item.val4})
</foreach>
此外还有一种把insert放入foreach循环里,但是此种批量插入效率很慢,相比以上这种方式慢了很多很多。所以还是优先推荐上述方式。