<insert id="insertOrder" parameterType="Integer" useGeneratedKeys="true" keyProperty="order_id"> insert into orders(user_id, total) select user_id, sum(total) from cart where user_id = #{userId} </insert> <insert id="insertOrderDetail" parameterType="Integer"> insert into order_detail(order_id, book_id, num, total) select #{order_id}, c.book_id, c.num, c.total from cart c where c.user_id = #{userId} </insert> 在mapper中的两个标签里,如何设置能让insertOrder执行完之后自动执行insertOrderDetail
时间: 2024-03-14 09:46:24 浏览: 305
MyBatis在insert插入操作时返回主键ID的配置(推荐)
可以在mapper文件中使用MyBatis的<selectKey>标签来实现该需求。具体操作如下:
1. 在insertOrder标签中使用<selectKey>标签,声明order_id为生成的主键,并将其返回给order_id参数。
```
<insert id="insertOrder" parameterType="Integer" useGeneratedKeys="true" keyProperty="order_id">
<selectKey keyProperty="order_id" orderType="BEFORE" resultType="java.lang.Integer">
SELECT nextval('order_seq')
</selectKey>
insert into orders(user_id, total)
select user_id, sum(total) from cart where user_id = #{userId}
</insert>
```
2. 在insertOrderDetail标签中使用order_id参数。
```
<insert id="insertOrderDetail" parameterType="Integer">
insert into order_detail(order_id, book_id, num, total)
select #{order_id}, c.book_id, c.num, c.total
from cart c
where c.user_id = #{userId}
</insert>
```
这样,当执行insertOrder时,会先生成order_id并返回给order_id参数,然后在执行insertOrderDetail时,使用该参数插入对应的order_detail记录。
阅读全文