7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MybatisでOracleに一括insert(ID自動増加なし)

Last updated at Posted at 2016-03-17

mybatisを利用して、OracleDBに一括insert方法を紹介します。
ID自動増加ではないパターン

ID自動増加パターン

mapperメソッド定義

引数:insert対象リスト
itemListを一括DBにinsertします。

int insertBatch(@Param ("itemList" ) List<ObjectClass> itemList);

mapping.xmlのSQL定義

## NGパターン

<insert id ="insertBatch" parameterType="java.util.List">
  insert into TABLEAAA (C1, C2)
  values
    <foreach collection ="itemList" item= "item"
      index= "index" separator =",">
      (#{item.c1},#{item.c2})
    </foreach >
</insert >

書き方は大丈夫そうな感じですが、実は下記エラーが発生します。
Cause: java.sql.BatchUpdateException : ORA-00933: SQLコマンドが正しく終了されていません。
; bad SQL grammar []; nested exception is java.sql.BatchUpdateException: ORA-00933: SQLコマンドが正しく終了されていません。
Oracleの場合は特別です。
## OKパターン1
INSERT ALLを利用します。

<insert id ="insertBatch" parameterType="java.util.List">
  INSERT ALL 
  <foreach collection ="itemList" item= "item">
    INTO TABLEAAA (C1, C2) values (#{item.c1},#{item.c2})
  </foreach >
  SELECT * FROM dual
</insert >

## OKパターン2
union allを利用します。

<insert id ="insertBatch" parameterType="java.util.List">
  insert into TABLEAAA (C1, C2)
   <foreach collection ="itemList" item= "item" separator= "union all">
    (select #{item.c1},#{item.c2} from dual)
   </foreach >
</insert >
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?