简体   繁体   中英

MyBatis insert all with generated ID

I'm trying to make an insert all method inside my mapper. The problem is with the the selectKey inside the foreach (it seems I cannot use it). If I call, from the outside, a nextVal method it returns always the same number.

<select id="nextValKey" resultType="java.lang.Long">
 SELECT MY_SEQUENCE.nextVal from dual
</select>

<insert id="insertAll" parameterType="list">
  INSERT ALL
  <foreach collection="items" item="item" index="i">
   <![CDATA[
    into MY_TABLE (ID)
    values (
    #{item.id, jdbcType=DECIMAL}
   ]]> 
  </foreach>
  SELECT * FROM dual
</insert>

If I understand correctly you generate ids for items via call to nextValKey .

The problem is that mybatis used cached value if you invoke the same select statement for the second time in the same session.

If you have query that returns different values each time you can instruct mybatis to clear the cache after statement execution (by default this is off for select and is on for insert , update and delete ):

<select id="nextValKey" resultType="java.lang.Long" flushCache="true">
   SELECT MY_SEQUENCE.nextVal from dual
</select>

I don't know Java nor MyBatis.

However, why would you want to use INSERT ALL in this case? It is usually used when you want to insert rows into different tables, using the same INSERT statement.

In your case, though - as far as I understand it - all you do is (pseudocode)

insert into my_table (id) a_sequence_of_numbers

If that's so, and as that "sequence_of_numbers" gets its value from my_sequence, then just do it as

insert into my_table (id)
  select my_sequence.nextval
  from dual
  connect by level <= 10;   -- it would insert 10 numbers

[EDIT: how to insert bunch of values]

You'd do it as simple as that:

SQL> create table my_table (id number);

Table created.

SQL> set timing on
SQL>
SQL> insert into my_table
  2    select level from dual
  3    connect by level <= 10000;

10000 rows created.

Elapsed: 00:00:00.02
SQL>

Or, if you insist on a sequence you created,

SQL> insert into my_table
  2    select seqa.nextval from dual
  3    connect by level <= 10000;

10000 rows created.

Elapsed: 00:00:00.08
SQL>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM