美文网首页
2018-03-04 web用户项目:批量删除 ----- 事务

2018-03-04 web用户项目:批量删除 ----- 事务

作者: 紫杉叶子 | 来源:发表于2018-03-05 07:56 被阅读0次
    笔记如下

    1.单个删除


    4.png
    • web层(DeleteOneCustomersServlet)
    //获得id
            String id = request.getParameter("id");
            
            //调用业务层去删除,将id带过去
            CustomerService cs = new CustomerService();
            
            cs.deleteOneCustomerById(id);
            //删除成功后再次查询 ---- 重定向到查询页面
            
            response.sendRedirect(request.getContextPath() + "/findall");
    
    • 业务层(CustomerService)
    
        //根据客户的id好去删除信息
        public void deleteOneCustomerById(String id) {
            // TODO Auto-generated method stub
            
            
            cdao.deleteOneById(id);
            
            
        }
    
    • dao层(CustomerDaoImpl)
    //单个删除
        /* (non-Javadoc)
         * @see com.chen.customers.dao.CustomerDao#deleteOneById(java.lang.String)
         */
        @Override
        public void deleteOneById(String id) {
            // TODO Auto-generated method stub
            
            QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
            try {
                runner.update("delete from customers where id=?", new Object[] {id});
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            
        }
    

    2.全删除

    • jsp
    <script type="text/javascript">
    //点击是否勾选全部的js代码
        function checkAllStatus() {
            
            //拿到最上面的
            var checkBtn = document.getElementById("checked");
            //alert(checkBtn.checked);
            
    
            //拿到所有name为ids的input
            var ids = document.getElementsByName("ids");
            
    ![4.png](https://img.haomeiwen.com/i10759518/ccd2eb7a175c88a1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
            for (var i = 0; i < ids.length; i++) {
                ids[i].checked = checkBtn.checked;
                
            }
            
    </script>
    
    
    
    
    
    <table border="1" align="center" width="100%">
                <tr>
                    <th>
                        设置状态<input type="checkbox" name="checkBtn" id="checked"  onclick="checkAllStatus();">
                    </th>
                    <th>客户姓名</th>
                    <th>客户性别</th>
                    <th>客户生日</th>
                    <th>客户邮箱</th>
                    <th>客户手机</th>
                    <th>客户爱好</th>
                    <th>客户类型</th>
                    <th>客户描述</th>
                    <th>操作</th>
                </tr>
                <c:forEach items="${customers}" var="customer">
                    <tr>
                        <td>
                            <input type="checkbox" name="ids" value="${customer.id}">
                        </td>
                        <td>${customer.name}</td>
                        <td>${customer.gender}</td>
                        <td>${customer.birthday}</td>
                        <td>${customer.email}</td>
                        <td>${customer.cellphone}</td>
                        <td>${customer.preference}</td>
                        <td>${customer.type}</td>
                        <td>${customer.description}</td>
                        <td>
                            <a href="javascript:void(0)" onclick="confrimDel('${customer.id}')">删除</a>
                            <a href="${pageContext.request.contextPath }/getonebyid?id=${customer.id}" >更新</a>
                            
                        </td>
                    </tr>
                </c:forEach>
                
            </table>
    
    4.png
    • web层(DeteleBatchServlet)
    //获得批量id
            String[] ids = request.getParameterValues("ids");
            
            ThreadLocal t;
            
            //传递ids给业务层,去删除
            CustomerService cs  = new CustomerService();
            cs.deleteBatch(ids);
            
            //重定向
            response.sendRedirect(request.getContextPath() + "/findall");
    
    • 业务层(CustomerService)
    //批量删除:批量删除,要么全部失败,要么全部成功-----事务
        //解决数据耦合 ----- ThreadLocal类
        public void deleteBatch(String[] ids) {
            // TODO Auto-generated method stub
            
            
            try {
                
                //开启事务 ----- set(conn)(ThreadLocal类)
                TransactionUtil.startTransaction();
                
                for (String id : ids) {
                    
                    //不能用cdao.deleteOneById(id)
                    cdao.deleteOneByIdInTransaction(id);
                }
    //          //提交事务
    //          conn.commit();
            
                TransactionUtil.commit();
            } catch (Exception e) {
                //有异常就回滚
                TransactionUtil.rollback();
                
            }finally {
                //释放资源
                TransactionUtil.relase();
                
            }
            
            
        }
    
    • dao层(CustomerDaoImpl)
    //在事务中的单个删除 
        @Override
        public void deleteOneByIdInTransaction(String id) throws SQLException {
            // TODO Auto-generated method stub
            
            QueryRunner runner = new QueryRunner();
            
            runner.update(TransactionUtil.getConnection(),"delete from customers where id=?", new Object[] {id});
            
            
        }
    
    • 工具类(TransactionUtil)
    //把得到连接及事务有关的方法写到此类中
    public class TransactionUtil {
        
        // 内部是维护了 一个 map , 这个map 的key 始终 都是 当前 的线程 
        private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
        
        private static DataSource ds = JdbcUtils.getDataSource();
        
        public static DataSource getDataSource(){
            return ds;
        }
        
        //  这里, 获得一个 connection  对象 
        public static Connection getConnection(){
            try {
                Connection conn = tl.get();
                if(conn==null){
                    //从数据连接池 中 取 一个连接 出来 
                    conn = ds.getConnection();
                    
                    //将 取出来  connection 放到 tl中去
                    tl.set(conn);
                }
                return conn;
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        
        // 开启 事务  
        // 结果 就是 返回了 一个 connection对象, 并且 将 返回的 connection放到了 threadlocal中 , 
        public static void startTransaction(){
            try {
                Connection conn = tl.get();
                if(conn==null){
                    conn = getConnection();
    //              tl.set(conn);
                }
                conn.setAutoCommit(false);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        public static void rollback(){
            try {
                Connection conn = tl.get();
                if(conn==null){
                    conn = getConnection();
    //              tl.set(conn);
                }
                conn.rollback();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        public static void commit(){
            try {
                Connection conn = tl.get();
                if(conn==null){
                    conn = getConnection();
    //              tl.set(conn);
                }
                conn.commit();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        public static void relase(){
            try {
                Connection conn = tl.get();
                if(conn!=null){
                    conn.close();
                    tl.remove();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:2018-03-04 web用户项目:批量删除 ----- 事务

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