帮我写一个用mybatis 完成批量扣减商品数量 的代码 包括mapper 和 mapper.xml
时间: 2024-09-11 12:03:56 浏览: 46
当你想用MyBatis完成批量扣减商品数量的操作,你需要创建一个Mapper接口、一个对应的XML映射文件以及一个Service层来调用这个Mapper。下面是一个简单的示例:
首先,创建Mapper接口(ItemMapper.java):
```java
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
public interface ItemMapper {
@Insert({
"BEGIN",
"UPDATE item SET stock = stock - #{quantity} WHERE id IN ",
"(SELECT item_id FROM order_items WHERE order_id = #{orderId})",
"AND stock > 0",
"COMMIT"
})
@Options(useGeneratedKeys = true, keyProperty = "itemId")
int deductStock(@Param("orderId") Long orderId, @Param("quantity") Integer quantity);
@Delete("DELETE FROM item WHERE id = #{itemId}")
void deleteItemById(Long itemId);
}
```
接着,创建Mapper XML配置文件(itemMapper.xml):
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yourpackage.ItemMapper">
<insert id="deductStock" parameterType="map">
<!-- SQL 更新语句 -->
<selectKey resultType="long" order="BEFORE" keyProperty="itemId">
SELECT LAST_INSERT_ID() AS itemId
</selectKey>
${script}
</insert>
<delete id="deleteItemById" parameterType="long">
DELETE FROM item WHERE id = #{itemId}
</delete>
</mapper>
```
注意:这里的`${script}`标签需要替换为之前在Java接口中的那行SQL,即`BEGIN...COMMIT`部分。
最后,在Service层或其他业务处理地方调用Mapper方法:
```java
@Service
public class ProductService {
private final ItemMapper itemMapper;
public ProductService(ItemMapper itemMapper) {
this.itemMapper = itemMapper;
}
public void deductStockForOrder(Long orderId, Integer quantity) {
int affectedRows = itemMapper.deductStock(orderId, quantity);
// 验证影响行数是否为预期,如果有事务管理,也可以在此检查事务状态
if (affectedRows <= 0) {
// 处理异常逻辑
}
}
}
```
阅读全文