<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> 前端只发送了一个调用insertOrder的请求,但我想执行完insertOrder后,能够自动的执行insertOrderDetail,在mapper中应该如何实现
时间: 2024-03-14 15:46:30 浏览: 55
您可以在mapper中使用Mybatis的<selectKey>标签来实现这个功能,具体方法如下:
1. 在insertOrder标签中添加<selectKey>标签,用于获取自动生成的order_id,如下所示:
```
<insert id="insertOrder" parameterType="Integer" useGeneratedKeys="true" keyProperty="order_id">
<selectKey keyProperty="order_id" resultType="java.lang.Integer" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
insert into orders(user_id, total)
select user_id, sum(total) from cart where user_id = #{userId}
</insert>
```
2. 在insertOrder标签的末尾添加<include>标签,用于调用insertOrderDetail标签,如下所示:
```
<insert id="insertOrder" parameterType="Integer" useGeneratedKeys="true" keyProperty="order_id">
<selectKey keyProperty="order_id" resultType="java.lang.Integer" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
insert into orders(user_id, total)
select user_id, sum(total) from cart where user_id = #{userId}
<include refid="insertOrderDetail"/>
</insert>
```
这样,在执行完insertOrder后,Mybatis会自动执行insertOrderDetail,并将order_id作为参数传递给insertOrderDetail。注意,在insertOrderDetail中,您需要使用#{order_id}来引用order_id参数。
这种方式可以实现两个insert语句的自动执行,并且可以保证在同一事务中执行,避免了数据不一致的问题。
阅读全文