mybatis批量插入和修改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循环里,但是此种批量插入效率很慢,相比以上这种方式慢了很多很多。所以还是优先推荐上述方式。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值