1. 程式人生 > 實用技巧 >mybatis批量插入oralce資料庫報錯java.sql.SQLException: ORA-00933: SQL 命令未正確結束

mybatis批量插入oralce資料庫報錯java.sql.SQLException: ORA-00933: SQL 命令未正確結束

轉自:https://blog.csdn.net/csdn_ss1991/article/details/80439777

簡述:需要向oracle資料庫批量插入資料,然後一直報錯,”java.sql.SQLException: ORA-00933: SQL 命令未正確結束“,然後各種百度,最終得到解決,現在總結一下,方便下次查詢。 知識點: 在使用foreach的時候最關鍵的也是最容易出錯的就是collection屬性,該屬性是必須指定的,但是在不同情況 下,該屬性的值是不一樣的,主要有一下3種情況: 1.如果傳入的是單引數且引數型別是一個List的時候,collection屬性值為list 2.如果傳入的是單引數且引數型別是一個array陣列的時候,collection的屬性值為array 3.如果傳入的引數是多個的時候,我們就需要把它們封裝成一個Map了,當然單引數也可以封裝成map 下面是解決辦法 第一種方式:
<
insert id="insertBatch" useGeneratedKeys="false"> insert into T_OPERATION_LOG (ID) select a.* from ( <foreach collection="list" item="log" index="index" close=")" open="(" separator="union"> select #{log.id} from dual
</foreach> )a </insert>

mybatis批量插入oracle時需要顯式指定為useGeneratedKeys="false"不然報錯~~~

第二種方式:

<insert id="insertBatch" useGeneratedKeys="false">
           insert into T_OPERATION_LOG
           (ID)
           <foreach collection="list" item="log" index="index" separator="union
all"> ( select #{log.id} from dual ) </foreach> </insert>
前兩種方式都是利用:insert into table(...) (select ... from dual) union all (select ... from dual) 如果ID是自增長的話,可以這樣寫:
<insert id="insertBatch" useGeneratedKeys="false">
INSERT INTO T_CITY_INDEX(
id,city_code
)
select SEQ_CITY_INDEX.NEXTVAL,cd.* from(
<foreach collection="list" item="item" index="index" close=")" open="(" separator="union">
select
#{item.cityCode,jdbcType=VARCHAR},
#{item.cityName,jdbcType=VARCHAR}
from dual
</foreach>
) cd
</insert>

第三種方式:

<insert id="insertBatch" useGeneratedKeys="false">
          insert all
           <foreach collection="list" item="log" index="index">
                into T_OPERATION_LOG
                (ID)
                values
                (#{log.id})
           </foreach>
           select 1 from dual
</insert>