java - How to use auto-generated ID in multiple INSERT statements within single MyBatis insert tag? - Stack Overflow

admin2025-04-16  7

I want to implement the following functionality in MyBatis:

  1. Execute two INSERT queries with a single insert tag
  2. Use the auto-incremented ID (id1) generated from the first INSERT in the second INSERT query
  3. Return the generated id1 after both INSERT queries are completed

Here's what I'm trying to achieve:

<insert id="insert-twice">
    insert into table1(name, password)
    values (#{name}, #{password}); --- id1 generated by auto_increment from first insert

    insert into table2(table1_id, score)
    values(#{id1}, #{score}) --- use id1 generated from first insert

    --- finally return id1
</insert>

Is it possible to write MyBatis code that works this way? If so, how can I implement it?"

I tried using useGeneratedKeys

<insert id="insert-twice" useGeneratedKeys="true" keyProperty="id">
    insert into table1(name, password)
    values (#{name}, #{password});
    
    insert into table2(table1_id, score)
    values(#{id}, #{score})
</insert>

But I got an error saying the ID wasn't available for the second insert.

转载请注明原文地址:http://www.anycun.com/QandA/1744746753a87030.html