2016-06-11 140 views
0

我有一個問題,假設我有最初說100條記錄,並且我在UI上顯示它們作爲用戶列表。現在我已經提供了通過單擊針對每條記錄放置的「取消激活」按鈕來停用號碼用戶的規定,然後我將所有「取消激活」的用戶捕獲到列表中並將其發送到DAO層[取消激活用戶的邏輯只是將'isDeleted'標誌設置爲true,iesoft delete因此,它與我更新已放入列表的多個記錄一樣好],有一個簡單的解決方案,寫一個for循環 - >遍歷列表 - >和每條記錄觸發一個查詢來更新isDeleted標誌爲true,但是如果我有5000條記錄要一次刪除,那麼它不可行。我已經聽到並實施了批量更新概念「插入」多個記錄一次,但我不明白我怎麼才能使用批量更新來更新多個記錄只有一個數據庫調用,請大家幫忙,插入的批量更新代碼是下面,批量更新更新多個記錄在春天mvc與mysql

private static final String INSERT_USER_PERMISSION = 
      "INSERT INTO permission_transaction(permissionId,userId,isDeleted) " 
      + "VALUES(?,?,?)"; 

@Transactional 
    public void addPermission(final UserVO userVo, final List<PermissionVO> permissionVoList) 
      throws Exception { 
     logger.info("Adding user permission, for userId: "+userVo.getUserId()); 

     try { 
      jdbc.batchUpdate(INSERT_USER_PERMISSION, new BatchPreparedStatementSetter() { 
       @Override 
       public void setValues(PreparedStatement ps, int i) throws SQLException { 

        PermissionVO permissionVo = permissionVoList.get(i); 
        ps.setInt(1, permissionVo.getPermissionId()); 
        ps.setInt(2, userVo.getUserId()); 
        ps.setBoolean(3, false); 
       } 
       @Override 
       public int getBatchSize() { 
        return permissionVoList.size(); 
       } 
      }); 
      logger.info("Exiting addPermission, for userId: "+userVo.getUserId()); 
     }catch (Exception e) { 
      logger.error("Error in adding user permission: " + e.getMessage(), e); 
      throw e; 
     } 

    } 

回答

0

嘿,我找到了解決辦法,這是我做什麼,

private static final String UPDATE_CLIENT_OWNER = 
      "UPDATE clientowner SET " 
      + "clientOwnerName=?," 
      + "clientOwnerPhone=?," 
      + "clientOwnerEmail=?," 
      + "lastUpdatedOn=NOW() " 
      + "WHERE clientOwnerId=?"; 
@Transactional 
    public void updateClientOwner(int clientId, List<ClientOwnerVO> clientOwnerVoList) throws Exception { 
     logger.info("Updating client Owner(s)"); 
     try{ 
      int[] count = jdbc.batchUpdate(UPDATE_CLIENT_OWNER, new BatchPreparedStatementSetter() { 
       @Override 
       public void setValues(PreparedStatement ps, int i) throws SQLException { 

        ClientOwnerVO clientOwnerVO = clientOwnerVoList.get(i); 
        ps.setString(1, clientOwnerVO.getClientOwnerName()); 
        ps.setString(2, VariableEncryption.encrypt(clientOwnerVO.getClientOwnerPhone(), clientOwnerVO.getCreatedOn())); 
        ps.setString(3, VariableEncryption.encrypt(clientOwnerVO.getClientOwnerEmail(), clientOwnerVO.getCreatedOn())); 
        ps.setInt(4, clientOwnerVO.getClientOwnerID()); 

       } 
       @Override 
       public int getBatchSize() { 
        return clientOwnerVoList.size(); 
       } 
      }); 
      logger.info("Exiting After successfully updating "+count.toString()+" client owners"); 


     }catch (Exception e) { 
      logger.error("Error in updating client owners: " + e.getMessage(), e); 
      throw e; 
     }