From 1d5a775dedff6d2e7817dcdac6305c6592cf099d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E5=BF=A0=E6=9E=97?= <170083662@qq.com> Date: Fri, 22 Aug 2025 17:50:55 +0800 Subject: [PATCH] =?UTF-8?q?fix(shop):=20=E4=BF=AE=E5=A4=8D=E4=BC=98?= =?UTF-8?q?=E6=83=A0=E5=88=B8=E9=A2=86=E5=8F=96=E5=8A=9F=E8=83=BD=E7=9A=84?= =?UTF-8?q?=E7=A9=BA=E6=8C=87=E9=92=88=E5=BC=82=E5=B8=B8=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 增加了对优惠券不存在的检查 -安全地检查和更新优惠券的已领取数量,避免空指针异常 - 在 SQL 查询中使用 COALESCE 函数安全地获取已领取数量 --- .../controller/ShopUserCouponController.java | 16 ++++++++++++++-- .../shop/mapper/xml/ShopCouponMapper.xml | 3 ++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/gxwebsoft/shop/controller/ShopUserCouponController.java b/src/main/java/com/gxwebsoft/shop/controller/ShopUserCouponController.java index 2c795f7..a9382b2 100644 --- a/src/main/java/com/gxwebsoft/shop/controller/ShopUserCouponController.java +++ b/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 userCouponList = shopUserCouponService.list( new LambdaQueryWrapper() .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("领取成功"); } diff --git a/src/main/java/com/gxwebsoft/shop/mapper/xml/ShopCouponMapper.xml b/src/main/java/com/gxwebsoft/shop/mapper/xml/ShopCouponMapper.xml index b4fcda5..6030a91 100644 --- a/src/main/java/com/gxwebsoft/shop/mapper/xml/ShopCouponMapper.xml +++ b/src/main/java/com/gxwebsoft/shop/mapper/xml/ShopCouponMapper.xml @@ -4,7 +4,8 @@ - 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