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>

 

posted @ 2020-09-12 21:13  yixiu868  阅读(1290)  评论(0编辑  收藏  举报