Mybatis批量增加,刪除,更新Oracle
最近需要用到Mybatis批量新增oracle資料庫,剛開始在網上找到的方法是都是更新mySQL的,試了一下發現不適合Oracle,後來發現正確的oracle批量新增的sql是:
<insert id="insertAttractionsBatch" parameterType="java.util.List">
insert into ATTRACTIONS (
ID, NAME, LONGITUDE, LATITUDE, UPDATE_TIME
)
<foreach collection="list" item="item" index="index" separator="union all" >
(select
#{item.id,jdbcType=VARCHAR}, #{item.name,jdbcType=VARCHAR}, #{item.longitude,jdbcType=DECIMAL}, #{item.updateTime,jdbcType=TIMESTAMP}
from dual)
</foreach>
</insert>
需要重點注意的是sql中沒有values,和<foreach>標籤中的(selece ..... from dual),MySql中的sql是這樣的:
新增:
<insert id="insertAttractionsBatch" parameterType="java.util.List">
insert into ATTRACTIONS (
ID, NAME, LONGITUDE, LATITUDE, UPDATE_TIME
)
<foreach collection="list" item="item" index="index" separator="union all" >
#{item.id,jdbcType=VARCHAR}, #{item.name,jdbcType=VARCHAR}, #{item.longitude,jdbcType=DECIMAL}, #{item.updateTime,jdbcType=TIMESTAMP}
</foreach>
</insert>
oracle更新不能按普通的方式,需要這樣:
<update id="updateAttractionsBatch" parameterType="java.util.List">
begin
<foreach collection="list" item="item" index="index" separator=";" >
update ATTRACTIONS
<set>
<if test="item.id!=null and item.id!=''">
id = #{item.id},
</if>
<if test="item.head!=null and item.head!=''">
HEAD = #{item.head},
</if>
</set>
where id = #{item.id}
</foreach>
;end;
</update>
刪除就與MySql一樣瞭如下:
<delete id="deleteAttractions" parameterType="java.util.List">
delete from ATTRACTIONS
<where>
<foreach collection="list" index="index" item="item" open="(" separator="or" close=")">
id=#{item.id}
</foreach>
</where>
</delete>