Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a list of objects using MyBatis 3

I've tried to insert a list in a database but I've got some the error: org.springframework.jdbc.BadSqlGrammarException: SqlSession operation; bad SQL grammar []; nested exception is java.sql.SQLException: ORA-00913: too many values (...).

The code that I've used:

<insert id="insertListMyObject" parameterType="java.util.List" >
INSERT INTO my_table
   (ID_ITEM,
    ATT1,
    ATT2)
    VALUES
   <foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
    #{item.idItem, jdbcType=BIGINT},
    #{item.att1, jdbcType=INTEGER},
    #{item.att2, jdbcType=STRING}
       </foreach>   
</insert>

My dao cals the method:

SqlSessionTemplate().insert(MAPPER+".insertListMyObject", parameterList);

Where the parameterList is:

List<MyObjects>.

Does someone have a clue about what's this error? Or if does exists a better way to do multiples inserts operation.

Many thanks!

like image 675
T Soares Avatar asked Dec 17 '22 05:12

T Soares


2 Answers

Set the separator as given below

separator="),("
like image 180
Frank Kemmer Avatar answered Dec 18 '22 20:12

Frank Kemmer


by using following query you may insert multiple records at a time using Mybatis and Oracle.

<insert id="insertListMyObject" parameterType="map" >
BEGIN
                            insert into table_name values (11,11);
                            insert into table_name2 values (11,112);
            END;
</insert>

this is how i did for oracle and it works. Note that parameterType=map is not necessary a map it can be anything according to your needs.

like image 43
Anas Avatar answered Dec 18 '22 19:12

Anas