Browse Source

fix(shop): 修复优惠券领取功能的空指针异常问题

- 增加了对优惠券不存在的检查
-安全地检查和更新优惠券的已领取数量,避免空指针异常
- 在 SQL 查询中使用 COALESCE 函数安全地获取已领取数量
main
科技小王子 2 days ago
parent
commit
1d5a775ded
  1. 16
      src/main/java/com/gxwebsoft/shop/controller/ShopUserCouponController.java
  2. 3
      src/main/java/com/gxwebsoft/shop/mapper/xml/ShopCouponMapper.xml

16
src/main/java/com/gxwebsoft/shop/controller/ShopUserCouponController.java

@ -120,7 +120,15 @@ public class ShopUserCouponController extends BaseController {
final User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录");
ShopCoupon coupon = couponService.getByIdRel(userCoupon.getCouponId());
if (coupon.getTotalCount() != -1 && coupon.getReceiveNum() >= coupon.getTotalCount()) return fail("已经被领完了");
// 检查优惠券是否存在
if (coupon == null) return fail("优惠券不存在");
// 安全地检查已领取数量,避免空指针异常
Integer receiveNum = coupon.getReceiveNum();
if (receiveNum == null) receiveNum = 0;
if (coupon.getTotalCount() != -1 && receiveNum >= coupon.getTotalCount()) return fail("已经被领完了");
List<ShopUserCoupon> userCouponList = shopUserCouponService.list(
new LambdaQueryWrapper<ShopUserCoupon>()
.eq(ShopUserCoupon::getCouponId, userCoupon.getCouponId())
@ -150,7 +158,11 @@ public class ShopUserCouponController extends BaseController {
}
userCoupon.setUserId(getLoginUserId());
shopUserCouponService.save(userCoupon);
coupon.setReceiveNum(coupon.getReceiveNum() + 1);
// 安全地更新已领取数量,避免空指针异常
Integer currentReceiveNum = coupon.getReceiveNum();
if (currentReceiveNum == null) currentReceiveNum = 0;
coupon.setReceiveNum(currentReceiveNum + 1);
couponService.updateById(coupon);
return success("领取成功");
}

3
src/main/java/com/gxwebsoft/shop/mapper/xml/ShopCouponMapper.xml

@ -4,7 +4,8 @@
<!-- 关联查询sql -->
<sql id="selectSql">
SELECT a.*
SELECT a.*,
COALESCE((SELECT COUNT(*) FROM shop_user_coupon suc WHERE suc.coupon_id = a.id AND suc.deleted = 0), 0) AS receive_num
FROM shop_coupon a
<where>
<if test="param.id != null">

Loading…
Cancel
Save