1. 启动类上加注解@EnableTransactionManagement
2. 在具体方法上加注解和回滚@Transactional(rollbackFor = Exception.class)
3. 抛出异常,回滚数据库信息
@Override
@Transactional(rollbackFor = Exception.class)
public String addSale(Sale sale) {
Integer price = sale.getPrice();
Integer quantity = sale.getQuantity();
Integer productid = sale.getProductid();
System.out.println(price+"====="+quantity+"===="+productid);
product.setProductid(productid);
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;
}
}
}
}