杭州网站专业制作/网站排名优化怎么做
相关文档
设置mysql唯一索引
https://blog.csdn.net/qq_39706570/article/details/102706845
实现目标
给表添加一条数据,该数据违反了表的索引唯一策略,要求java程序处理该异常。
控制层代码(这里以用户新增重复商品到购物车为例)
// 添加购物车@PostMapping("/addShoppingCart")@ResponseBodypublic Map<String, Object> addShoppingCart(Commodity commodity, String customerId) {Map<String, Object> resultMap = new HashMap<String, Object>();Map<String, Object> map = new HashMap<String, Object>();map.put("commodity", commodity);map.put("customerId", customerId);try {//向购物车新增商品AppShoppingCartService.addShoppingCart(map);} catch (Exception e) {//如果抛出的异常是重复索引的类型if (e instanceof DuplicateKeyException) {resultMap.put("code", "0");resultMap.put("msg", "新增失败,请不要重复添加商品到购物车。");return resultMap;}else {//这里可以根据项目需求写其他业务。throw e;}}resultMap.put("code", "0");resultMap.put("msg", "新增成功。");return resultMap;}