事务异常回滚

1. 启动类上加注解@EnableTransactionManagement

2. 在具体方法上加注解和回滚@Transactional(rollbackFor = Exception.class)

3. 抛出异常,回滚数据库信息

    @Override
//    出售商品并且减库存的方法 此处应声明为事务
    @Transactional(rollbackFor = Exception.class)
    public String addSale(Sale sale) {
//        Product product = new Product();
        Integer price = sale.getPrice();
        Integer quantity = sale.getQuantity(); //得到销售数量
        Integer productid = sale.getProductid(); //得到销售商品id
        System.out.println(price+"====="+quantity+"===="+productid);
        product.setProductid(productid); //设置销售的商品的id
        //得到商品库存数量
        Product product1 = productMapper.selectById(sale);
        Integer quantity1 = product1.getQuantity();
        Product product = this.product.setQuantity(quantity1 - quantity);//得到商品售出后现有库存
        if(product.getQuantity() >= 0){
            productMapper.updateById(product); //将商品信息更新
            sale.setTotalprice(quantity*price); //算出总价格
            String time = GetTime.getTime();
            sale.setSaledate(time);
            String insert = String.valueOf(saleMapper.insert(sale));
            return insert;
        }else{
            String msg = "库存不足";
//            如果库存不狗抛出异常
            try{
                throw new RuntimeException();
            }catch(RuntimeException e){
                e.printStackTrace();
                throw new RuntimeException("发生异常了..");
            }finally{
                return msg;
            }
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值