1. Dao层
BrandMapper接口写方法
写注解,映射ids这个数组
/**
* 批量删除
* @param ids
*/
void deleteByIds(@Param("ids") int[] ids);
xml映射文件
<delete id="deleteByIds">
delete from tb_brand where id
in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
;
</delete>
2. Service层
@Override
public void deleteByIds(int[] ids) {
//2. 获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//3. 获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4. 调用方法
mapper.deleteByIds(ids);
sqlSession.commit();//提交事务
//5. 释放资源
sqlSession.close();
}
3. Web层
BrandServlet
/**
* 批量删除
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 接收数据 [1,2,3]
BufferedReader reader = request.getReader();
String s = reader.readLine();//json字符串
//2. 转为int[]
int[] ints = JSON.parseObject(s, int[].class);
//3. 调用service方法
brandService.deletByIds(ints);
//4. 响应成功的标识
response.getWriter().write("success");
}
前端页面
// 批量删除
deleteByIds(){
// 弹出确认提示框
this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
//用户点击确认按钮
//1. 创建id数组 [1,2,3], 从 this.multipleSelection 获取即可
for (let i = 0; i < this.multipleSelection.length; i++) {
let selectionElement = this.multipleSelection[i];
this.selectedIds[i] = selectionElement.id;
}
//2. 发送AJAX请求
var _this = this;
// 发送ajax请求,添加数据
axios({
method:"post",
url:"http://localhost:8080/brand-project/brand/deleteByIds",
data:_this.selectedIds
}).then(function (resp) {
if(resp.data == "success"){
//删除成功
// 重新查询数据
_this.selectAll();
// 弹出消息提示
_this.$message({
message: '恭喜你,删除成功',
type: 'success'
});
}
})
}).catch(() => {
//用户点击取消按钮
this.$message({
type: 'info',
message: '已取消删除'
});
});
}