SSM + MySQL批量删除操作

  最近项目中有个购物车功能需要能够选中商品,然后批量删除的操作,也可以单个删除,其实代码很简单就能实现。

  这里需要注意的就是你前端是怎么传值的,我这里采用的数组的形式,用 ‘,’隔开。

  然后控制层代码如下:

 1 public Object DeleteShopping(HttpSession session, @RequestBody Map map) {
 2 
 3         JSONObject json = new JSONObject();
 4 
 5         String id = (String) map.get("ShoppingID");  //首先拿到前端传递进来的数组,然后放入字符串对象中
 6 
 7         List<Object> list = new ArrayList<>();
 8 
 9         String[] str = id.split(",");  //这里以逗号分隔来确认每个ID是什么,放入list数组中
10   
11         for (int i = 0; i < str.length; i++) {
12 
13             list.add(str[i]);    //循环将其添加到List集合中
14         }
15 
16         Integer is = applyService.DeleteShopping(list);
17 
18   
19 20 if (is > 0) { 21 22 json.put("msg", "删除成功!"); 23 json.put("code", "1"); 24 } 25 } else { 26 json.put("code", "0"); 27 json.put("error", "无法请求!"); 28 } 29 return json; 30 }

  

   我们使用的MyBatis,所以Mapper.xml中的SQL语句如下:

 1 <delete id="DeleteShopping" parameterType="java.util.List">
 2         <!-- delete from emp where empno in(7789,7790) -->
 3         <!-- forEach : 用来循环 collection : 用来指定循环的数据的类型 可以填的值有:array,list,map item
 4             : 循环中为每个循环的数据指定一个别名 index : 循环中循环的下标 open : 开始 close : 结束 separator : 数组中元素之间的分隔符 -->
 5         DELETE FROM ShoppingCart WHERE ShoppingID IN
 6         <foreach collection="list" item="arr" open="("
 7                  separator="," close=")">
 8             #{arr}
 9         </foreach>
10     </delete>

  至此,批量删除则已经实现,很简单的一个列子,就不多讲了。

原文地址:https://www.cnblogs.com/Wang352051443/p/9802705.html