I want to implement the following functionality in MyBatis:
- Execute two INSERT queries with a single insert tag
- Use the auto-incremented ID (id1) generated from the first INSERT in the second INSERT query
- 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.