基于maven+ssm的增删改查之批量删除

时间:2022-07-23
本文章向大家介绍基于maven+ssm的增删改查之批量删除,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

首先将之前的删除单个的eq(1)改为eq(2),因为我们新增了一个多选项。

然后是在delete.js中加入:

//点击全部删除,就批量删除
$("#emp_delete_all_btn").click(function(){
    var empNames = "";
    var del_idstr = "";
    //遍历选中的,获取其姓名和id
    $.each($(".check_item:checked"),function(){
        //this
        empNames += $(this).parents("tr").find("td:eq(2)").text()+",";
        //组装员工id字符串
        del_idstr += $(this).parents("tr").find("td:eq(1)").text()+"-";
    });
    //去除多余的逗号
    empNames = empNames.substr(0,empNames.length-1);
    //去除多余的短横线
    del_idstr = del_idstr.substr(0,del_idstr.length-1);
    //alert(del_idstr);
    if(confirm("确认删除【"+empNames+"】吗?")){
        $.ajax({
            url:"/curd_ssm/emp/"+del_idstr,
            type:"DELETE",
            success:function(result){
                alert(result.msg);
                to_page(currentNum);
            }
        });
    }
});

将多选id组合成1-2-3-4的形式传给后端,可以发现我们的请求地址是和单个删除是同一个地址,因此要对删除方法进行改造。

EmployeeController.java

    @ResponseBody
    @RequestMapping(value="/emp/{ids}",method=RequestMethod.DELETE)
    public Msg deleteEmpByid(@PathVariable("ids") String ids) {
        if(ids.contains("-")) {
            List<Integer> del_ids = new ArrayList<>();
            String[] str_ids = ids.split("-");
            //组装id集合
            for (String string : str_ids) {
                del_ids.add(Integer.parseInt(string));
            }
            employeeService.batchDelete(del_ids);
        }else {
            Integer id = Integer.parseInt(ids);
            employeeService.deleteEmp(id);
        }
        return Msg.success();
    }

我们修改接收的字符串为ids,如果是单个id,就执行之前的删除单条数据,如果包含“-”符号,说明是多条数据,首先切分成数组,然后装换成Integer类型并用List<Integer>进行接收,最后执行批量删除操作。

EmployeeService.java

    public void batchDelete(List<Integer> ids);

EmployeeServiceImpl.java

    @Override
    public void batchDelete(List<Integer> ids) {
        // TODO Auto-generated method stub
        EmployeeExample employeeExample = new EmployeeExample();
        Criteria criteria = employeeExample.createCriteria();
        criteria.andEmpIdIn(ids);
        employeeMapper.deleteByExample(employeeExample);
    }

最后启动服务器:

点击批量删除:

点击确定:

点击确定:

至此,基于maven+ssm的增删改查终于全部完成了 。。。。