資料庫批量操作(批量更新,批量插入)
阿新 • • 發佈:2018-11-16
資料庫的批量操作
為了儘可能提高我們的sql執行效率,一般我們針對多條資料的操作,使用批量更新或者批量插入的方式 方式如下:
--批量插入
<insert id="saveUserList" parameterType="java.util.List">
insert into test
(id,name)
values
<foreach collection="list" item="user" separator=",">
(
#{ user.id},
#{user.name}
)
</foreach>
</insert>
批量更新(使用方式一效率較高)
方式一:
<update id="batchUpdateUser" parameterType="java.util.Map" >
update user t
set
pay_status=r.status,
updated_date =now(),
updated_by= #{paramMap.currentUser}
from (
<foreach collection="paramMap.list" item="i" separator="union all">
select #{i.id}::text id,
#{i.status}::text status
</foreach>
) r
where r.id=t.id
</update>
方式二:
<update id="batchUpdateUser" >
update user
set name =
<foreach collection="list" item="item" index="index"
separator=" " open="case ID" close="end">
when #{item.id} then
#{item.name}
</foreach>
where id in
<foreach collection="list" item="item" index="index"
separator="," open="(" close=")">
#{item.id,jdbcType=VARCHAR}
</foreach>
</update>
```