2018-03-04 web用戶項目:批量刪除 ----- 事務(wù)處理

筆記如下

1.單個刪除


4.png
  • web層(DeleteOneCustomersServlet)
//獲得id
        String id = request.getParameter("id");
        
        //調(diào)用業(yè)務(wù)層去刪除,將id帶過去
        CustomerService cs = new CustomerService();
        
        cs.deleteOneCustomerById(id);
        //刪除成功后再次查詢 ---- 重定向到查詢頁面
        
        response.sendRedirect(request.getContextPath() + "/findall");
  • 業(yè)務(wù)層(CustomerService)

    //根據(jù)客戶的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](http://upload-images.jianshu.io/upload_images/10759518-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>
                    設(shè)置狀態(tài)<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給業(yè)務(wù)層,去刪除
        CustomerService cs  = new CustomerService();
        cs.deleteBatch(ids);
        
        //重定向
        response.sendRedirect(request.getContextPath() + "/findall");
  • 業(yè)務(wù)層(CustomerService)
//批量刪除:批量刪除,要么全部失敗,要么全部成功-----事務(wù)
    //解決數(shù)據(jù)耦合 ----- ThreadLocal類
    public void deleteBatch(String[] ids) {
        // TODO Auto-generated method stub
        
        
        try {
            
            //開啟事務(wù) ----- set(conn)(ThreadLocal類)
            TransactionUtil.startTransaction();
            
            for (String id : ids) {
                
                //不能用cdao.deleteOneById(id)
                cdao.deleteOneByIdInTransaction(id);
            }
//          //提交事務(wù)
//          conn.commit();
        
            TransactionUtil.commit();
        } catch (Exception e) {
            //有異常就回滾
            TransactionUtil.rollback();
            
        }finally {
            //釋放資源
            TransactionUtil.relase();
            
        }
        
        
    }
  • dao層(CustomerDaoImpl)
//在事務(wù)中的單個刪除 
    @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)
//把得到連接及事務(wù)有關(guān)的方法寫到此類中
public class TransactionUtil {
    
    // 內(nèi)部是維護了 一個 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){
                //從數(shù)據(jù)連接池 中 取 一個連接 出來 
                conn = ds.getConnection();
                
                //將 取出來  connection 放到 tl中去
                tl.set(conn);
            }
            return conn;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    
    // 開啟 事務(wù)  
    // 結(jié)果 就是 返回了 一個 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);
        }
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,650評論 18 399
  • 一. Java基礎(chǔ)部分.................................................
    wy_sure閱讀 4,011評論 0 11
  • 沒有任何面試通知,也沒有入職通知,一直安安靜靜的。 我一如既往的一早起床,打開電腦,做著我要提高的事情 看了一些項...
    soso_3793閱讀 295評論 0 0

友情鏈接更多精彩內(nèi)容