美文网首页
Mybatis实现数据库数据批量删除

Mybatis实现数据库数据批量删除

作者: 黎涛note | 来源:发表于2019-10-30 19:33 被阅读0次
使用mybatis将数据库中的记录
1.前台jsp页面,将要删除的记录选中,通过将记录的id对记录进行区别,请求方法为post;
2.使用jQuery,js对页面进行全选,或全部清除选择。
3.servlet控制层,通过req对象获取id,然后将存放id数组进行参数类型转换,转为int[];
4.sevice服务层,使用数据库连接池,获取SqlSession实例对象,由session对象获取Mybatis框架创建的接口的实例,通过声明接口中处理批量删除的方法,配置接口对应的xml配置文件。
1,前台jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>商品列表</title>
    <script type="text/javascript" src="/mybatis_demo1/js/jquery-1.11.2.js"></script>
    <script type="text/javascript">
           $(function(){
               $("#checkAll").click(function(){
                   var ckd=this.checked;
                   if(ckd)
                       $("input[name='checkedPrdId']").prop("checked",true);
                   else
                       $("input[name='checkedPrdId']").removeProp("checked");
               });
           });
    </script>
    <style type="text/css">
        table,table td{
            border:1px solid black;
        }
        
        table {
            border-collapse: collapse;
        }
        
        table td{
            width: 200px;
            height: 20px;
        }
    </style>
</head>
<body>
prdList

    <c:if test="${not empty prdList}">
        <form action="/mybatis_demo1/prdServlet?flag=batchDelete" method="post">
            <input type="submit" value="批量删除"/>${msg} <br/>
            <table>
                <thead>
                  <tr>
                      <td><input type="checkbox" id="checkAll" /></td>
                      <td>商品编号</td>
                      <td>商品类别</td>
                      <td>商品名称</td>
                      <td>商品价格</td>
                      <td>商品描述</td>
                  </tr>
                </thead>
                <tbody>
                    <c:forEach items="${prdList}" var="prd">
                            <tr>
                                  <td><input type="checkbox" name="checkedPrdId" value="${prd.prdId}" /></td>
                                  <td>${prd.prdId}</td>
                                  <td>${prd.typeId}</td>
                                  <td>${prd.prdName}</td>
                                  <td>${prd.price}</td>
                                  <td>${prd.desc}</td>
                            </tr>
                    </c:forEach>
                 </tbody>
            </table>
         </form>
    </c:if>
</body>
</html>
2.servlet类的post方法的实现
package com.xixi.demo.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.javafx.collections.MappingChange.Map;
import com.xixi.demo.common.Constants;
import com.xixi.demo.service.ProductService;
import com.xixi.demo.service.ProductTypeService;
import com.xixi.demo.vo.ProductInfo;
import com.xixi.demo.vo.ProductTypeInfo;

@WebServlet(urlPatterns="/prdServlet")
public class ProductServlet extends BaseServlet {
    
    private ProductService productService = new ProductService();
    private ProductTypeService productTypeService = new ProductTypeService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String flag = req.getParameter("flag");
        if("add".equals(flag)){
            ...
        }else if("search".equals(flag)){
            ...
        }else if("batchDelete".equals(flag)){
            int count = 0; 
            String[] values = req.getParameterValues("checkedPrdId");
            if(values!=null&&values.length>0 ){
                int[] prdId = new int[values.length];
                for(int i=0; i<values.length; i++){
                    prdId[i] = Integer.parseInt(values[i]);
                }
                count = this.productService.batchDelete(prdId); 
            }
            req.setAttribute("msg", "删除"+count+"条记录!");
             //获取产品列表
             List<ProductInfo> prdList = this.productService.getAllProducts();
             req.setAttribute("prdList", prdList);
             req.getRequestDispatcher("/prd/prd_list.jsp").forward(req, resp);
        }
    }
}

3.service层实现
package com.xixi.demo.service;

import com.sun.javafx.collections.MappingChange.Map;
import com.xixi.demo.common.Constants;
import java.util.HashMap;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.xixi.demo.common.DBUtils;
import com.xixi.demo.dao.ProductMapper;
import com.xixi.demo.vo.ProductInfo;

public class ProductService {
    /**
     * 
     *获取所有产品 
     * 
     * @return
     */
    public List<ProductInfo> getAllProducts() {
    ...
    }

    /**
     * 
     * 商品检索
     * 
     * @param condition
     * @param pageNum
     * @return
     */
    public List<ProductInfo> search(HashMap<String, Object> condition,  int pageNum) {
        ...
    }
    /**
     * 
     * 获取总页数
     * 
     * @param condition
     * @return
     */
    public int getPageCount(HashMap<String, Object> condition) {
           ...
    }
    /**
     * 批量删除
     * 
     * @param prdId
     * @return
     */
    public int batchDelete(int[] prdId) {
        SqlSession session = DBUtils.getSqlSession();
        ProductMapper prdMapper = session.getMapper(ProductMapper.class);
        int count=0;
        try {
            count = prdMapper.batchDelete(prdId);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return count;
    }

}

4.DAO层的mybatis框架接口实现
package com.xixi.demo.dao;

import java.util.HashMap;
import java.util.List;

import com.sun.javafx.collections.MappingChange.Map;
import com.xixi.demo.vo.ProductInfo;

public interface ProductMapper {
    //获取所有的产品
    List<ProductInfo> getAllProducts();
    //通过某一个产品编号查询产品信息
    ProductInfo getInfoById(Integer prdId);
    //录入新的商品
    int saveInfo(ProductInfo info);
    //检索商品
    List<ProductInfo> search(HashMap<String, Object> condition);
    //获取产品记录条数
    int getRecordCount(HashMap<String, Object> condition);
    //批量删除
    int batchDelete(int[] prdId);
}
5.DAO层的mybatis框架接口对应的xml配置文件的实现
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 
    <delete id="batchDelete" parameterType="_int[]">
         delete from products where productId IN
         <foreach collection="array" open="(" close=")" separator="," item="id">#{id}</foreach>
    </delete>
</mapper>

注意:

mybatis对于批量删除的过程中,参数为一个数组的情况,我们采用mybatis提供的<foreach>标签将参数进行逐个与数据库id进行比对,完成批量删除操作。

相关文章

网友评论

      本文标题:Mybatis实现数据库数据批量删除

      本文链接:https://www.haomeiwen.com/subject/rpdavctx.html