Mybatis批量更新数据库与批量插入数据库(以oracle为例)

时间:2021-01-10 15:28:34

一、批量更新

1、普通写法(一条记录update一次,性能比较差,容易造成阻塞。不建议使用)

<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>

2、使用case when语法来实现这个功能(推荐使用)

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'
END
WHERE id IN (1,2,3)

这条sql的意思是,如果id为1,则name的值为name1,title的值为New Title1;依此类推。

mybatis的XML文件配置

<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>

二、批量插入mybatis的XML文件配置

<insert id="insertMutil" parameterType="java.util.List">
insert all
<foreach collection="list" item="item" index="index"
separator=" ">
into SPSZMBB (ID, MBMC, HDCS, ZDHDS, SHID, FJS, SZSJ,SZRY)
values
(#{item.id},#{item.mbmc},#{item.hdcs},#{item.zdhds},#{item.shid},#{item.fjs},#{item.szsj},#{item.szry})
</foreach>
select 1 from dual
</insert>