Example usage for java.sql PreparedStatement addBatch

List of usage examples for java.sql PreparedStatement addBatch

Introduction

In this page you can find the example usage for java.sql PreparedStatement addBatch.

Prototype

void addBatch() throws SQLException;

Source Link

Document

Adds a set of parameters to this PreparedStatement object's batch of commands.

Usage

From source file:org.forgerock.openidm.repo.jdbc.impl.GenericTableHandler.java

/**
 * Internal recursive function to add/write properties.
 * If batching is enabled, prepared statements are added to the batch and only executed if they hit the max limit.
 * After completion returns the number of properties that have only been added to the batch but not yet executed.
 * The caller is responsible for executing the batch on remaining items when it deems the batch complete.
 *
 * If batching is not enabled, prepared statements are immediately executed.
 *
 * @param fullId the full URI of the resource the belongs to
 * @param dbId the generated identifier to link the properties table with the main table (foreign key)
 * @param localId the local identifier of the resource these properties belong to
 * @param value the JSON value with the properties to write
 * @param connection the DB connection//  w  w w. ja v a2  s.c  o  m
 * @param propCreateStatement the prepared properties insert statement
 * @param batchingCount the current number of statements that have been batched and not yet executed on the prepared statement
 * @return status of the current batchingCount, i.e. how many statements are not yet executed in the PreparedStatement
 * @throws SQLException if the insert failed
 */
private int writeValueProperties(String fullId, long dbId, String localId, JsonValue value,
        Connection connection, PreparedStatement propCreateStatement, int batchingCount) throws SQLException {

    for (JsonValue entry : value) {
        JsonPointer propPointer = entry.getPointer();
        if (cfg.isSearchable(propPointer)) {
            String propkey = propPointer.toString();
            if (entry.isMap() || entry.isList()) {
                batchingCount = writeValueProperties(fullId, dbId, localId, entry, connection,
                        propCreateStatement, batchingCount);
            } else {
                String propvalue = null;
                Object val = entry.getObject();
                if (val != null) {
                    propvalue = StringUtils.left(val.toString(), getSearchableLength());
                }
                String proptype = null;
                if (propvalue != null) {
                    proptype = entry.getObject().getClass().getName(); // TODO: proper type info
                }
                if (logger.isTraceEnabled()) {
                    logger.trace("Populating statement {} with params {}, {}, {}, {}, {}",
                            queryMap.get(QueryDefinition.PROPCREATEQUERYSTR), dbId, localId, propkey, proptype,
                            propvalue);
                }
                propCreateStatement.setLong(1, dbId);
                propCreateStatement.setString(2, propkey);
                propCreateStatement.setString(3, proptype);
                propCreateStatement.setString(4, propvalue);
                logger.debug("Executing: {}", propCreateStatement);
                if (enableBatching) {
                    propCreateStatement.addBatch();
                    batchingCount++;
                } else {
                    int numUpdate = propCreateStatement.executeUpdate();
                }
                if (logger.isTraceEnabled()) {
                    logger.trace("Inserting objectproperty id: {} propkey: {} proptype: {}, propvalue: {}",
                            fullId, propkey, proptype, propvalue);
                }
            }
            if (enableBatching && batchingCount >= maxBatchSize) {
                int[] numUpdates = propCreateStatement.executeBatch();
                if (logger.isDebugEnabled()) {
                    logger.debug("Batch limit reached, update of objectproperties updated: {}",
                            Arrays.asList(numUpdates));
                }
                propCreateStatement.clearBatch();
                batchingCount = 0;
            }
        }
    }

    return batchingCount;
}

From source file:com.flexive.ejb.beans.structure.TypeEngineBean.java

private void storeTypeOptions(Connection con, String table, String primaryColumn, long id, // Long assignmentId,
        List<FxStructureOption> options, boolean update) throws SQLException, FxInvalidParameterException {
    PreparedStatement ps = null;
    try {/*from  w w  w .j a  v a2  s  .c  om*/
        if (update) {
            ps = con.prepareStatement("DELETE FROM " + table + " WHERE " + primaryColumn + "=?");
            ps.setLong(1, id);
            ps.executeUpdate();
            ps.close();
        }

        if (options == null || options.size() == 0)
            return;
        //                                                        1                 2      3           4        5
        ps = con.prepareStatement("INSERT INTO " + table + " (" + primaryColumn
                + ",OPTKEY,MAYOVERRIDE,ISINHERITED,OPTVALUE)VALUES(?,?,?,?,?)");
        for (FxStructureOption option : options) {
            ps.setLong(1, id);
            if (StringUtils.isEmpty(option.getKey()))
                throw new FxInvalidParameterException("key", "ex.structure.option.key.empty",
                        option.getValue());
            ps.setString(2, option.getKey());
            ps.setBoolean(3, option.isOverridable());
            ps.setBoolean(4, option.getIsInherited());
            ps.setString(5, option.getValue());
            ps.addBatch();
        }
        ps.executeBatch();
    } finally {
        if (ps != null)
            ps.close();
    }
}

From source file:org.rhq.enterprise.server.measurement.CallTimeDataManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void insertCallTimeDataValues(Set<CallTimeData> callTimeDataSet) {
    int[] results;
    String insertValueSql;//  ww  w.j a  v  a  2s  .co  m
    PreparedStatement ps = null;
    Connection conn = null;

    try {
        conn = rhqDs.getConnection();
        DatabaseType dbType = DatabaseTypeFactory.getDatabaseType(conn);

        if (dbType instanceof Postgresql83DatabaseType) {
            Statement st = null;
            try {
                // Take advantage of async commit here
                st = conn.createStatement();
                st.execute("SET synchronous_commit = off");
            } finally {
                JDBCUtil.safeClose(st);
            }
        }

        if (dbType instanceof PostgresqlDatabaseType || dbType instanceof OracleDatabaseType
                || dbType instanceof H2DatabaseType) {
            String valueNextvalSql = JDBCUtil.getNextValSql(conn, "RHQ_calltime_data_value");
            insertValueSql = String.format(CALLTIME_VALUE_INSERT_STATEMENT, valueNextvalSql);
        } else if (dbType instanceof SQLServerDatabaseType) {
            insertValueSql = CALLTIME_VALUE_INSERT_STATEMENT_AUTOINC;
        } else {
            throw new IllegalArgumentException("Unknown database type, can't continue: " + dbType);
        }

        ps = conn.prepareStatement(insertValueSql);
        for (CallTimeData callTimeData : callTimeDataSet) {
            ps.setInt(7, callTimeData.getScheduleId());
            Set<String> callDestinations = callTimeData.getValues().keySet();
            for (String callDestination : callDestinations) {
                CallTimeDataValue callTimeDataValue = callTimeData.getValues().get(callDestination);
                ps.setLong(1, callTimeDataValue.getBeginTime());
                ps.setLong(2, callTimeDataValue.getEndTime());
                ps.setDouble(3, callTimeDataValue.getMinimum());
                ps.setDouble(4, callTimeDataValue.getMaximum());
                ps.setDouble(5, callTimeDataValue.getTotal());
                ps.setLong(6, callTimeDataValue.getCount());
                ps.setString(8, callDestination);
                ps.addBatch();
            }
        }

        results = ps.executeBatch();

        int insertedRowCount = 0;
        for (int i = 0; i < results.length; i++) {
            if ((results[i] != 1) && (results[i] != -2)) // Oracle likes to return -2 becuase it doesn't track batch update counts
            {
                throw new MeasurementStorageException("Failed to insert call-time data value rows - result ["
                        + results[i] + "] for batch command [" + i + "] does not equal 1.");
            }

            insertedRowCount += results[i] == -2 ? 1 : results[i]; // If Oracle returns -2, just count 1 row;
        }

        notifyAlertConditionCacheManager("insertCallTimeDataValues",
                callTimeDataSet.toArray(new CallTimeData[callTimeDataSet.size()]));

        if (insertedRowCount > 0) {
            MeasurementMonitor.getMBean().incrementCalltimeValuesInserted(insertedRowCount);

            log.debug("Inserted " + insertedRowCount + " call-time data value rows.");
        }

    } catch (SQLException e) {
        logSQLException("Failed to persist call-time data values", e);
    } catch (Throwable t) {
        log.error("Failed to persist call-time data values", t);
    } finally {
        JDBCUtil.safeClose(conn, ps, null);
    }

}

From source file:at.rocworks.oa4j.logger.dbs.NoSQLJDBC.java

public int storeData(DataList list) {
    try {//  www  .  ja  v a2s .c om
        Connection conn = dataSourceWrite.getConnection();
        if (conn != null) {
            int i;
            DataItem item;
            EventItem event;
            Object tag;

            conn.setAutoCommit(false);
            PreparedStatement stmt;

            Date t1 = new Date();

            stmt = conn.prepareStatement(sqlInsertStmt);
            for (i = 0; i <= list.getHighWaterMark() && (item = list.getItem(i)) != null; i++) {
                if (!(item instanceof EventItem))
                    continue;
                event = (EventItem) item;
                ValueItem val = event.getValue();

                tag = this.getTagOfDp(event.getDp());
                if (tag == null)
                    continue;

                if (tag instanceof Long)
                    stmt.setLong(1, (Long) tag);
                else if (tag instanceof String)
                    stmt.setString(1, (String) tag);

                java.sql.Timestamp ts = new java.sql.Timestamp(event.getTimeMS());
                ts.setNanos(event.getNanos());

                stmt.setTimestamp(2, ts, cal);

                Double dval = val.getDouble();
                if (dval != null) {
                    stmt.setDouble(3, dval);
                } else {
                    stmt.setNull(3, Types.DOUBLE);
                }

                // value_string                    
                stmt.setString(4, val.getString());

                // value_timestamp
                if (val.getTimeMS() != null)
                    stmt.setTimestamp(5, new java.sql.Timestamp(val.getTimeMS()), cal);
                else
                    stmt.setNull(5, Types.TIMESTAMP);

                // status, manager, user
                if (event.hasAttributes()) {
                    stmt.setLong(6, event.getStatus());
                    stmt.setInt(7, event.getManager());
                    stmt.setInt(8, event.getUser());
                } else {
                    stmt.setNull(6, Types.INTEGER);
                    stmt.setNull(7, Types.INTEGER);
                    stmt.setNull(8, Types.INTEGER);
                }

                //JDebug.out.log(Level.FINE, "{0}:{1}/{2} [{3}]", new Object[] {i, element_id.toString(), ts.toString(), item.toString()});

                stmt.addBatch();
            }
            try {
                stmt.executeBatch(); // TODO check result? int[] res =
            } catch (BatchUpdateException ex) {
                JDebug.out.log(Level.SEVERE, "Batch exception {0} update count {1}.",
                        new Object[] { ex.getErrorCode(), ex.getUpdateCounts().length });
                JDebug.StackTrace(Level.SEVERE, ex);
            } catch (SQLException ex) {
                SQLException current = ex;
                do {
                    JDebug.out.log(Level.SEVERE, "SQL exception {0}.", new Object[] { ex.getErrorCode() });
                    JDebug.StackTrace(Level.SEVERE, current);
                } while ((current = current.getNextException()) != null);
                //                    for (i = 0; i <= list.getHighWaterMark() && (item = list.getItem(i)) != null; i++) {
                //                        JDebug.out.log(Level.INFO, "{0}", item.toJSONObject());
                //                    }
            }
            Date t2 = new Date();
            stmt.close();

            afterInsert(conn);

            conn.commit();
            conn.close();
            addServerStats(list.getHighWaterMark(), t2.getTime() - t1.getTime());
            return INoSQLInterface.OK;
        } else {
            JDebug.StackTrace(Level.SEVERE, "no connection!");
            return INoSQLInterface.ERR_REPEATABLE;
        }
    } catch (Exception ex) {
        JDebug.StackTrace(Level.SEVERE, ex);
        return INoSQLInterface.ERR_REPEATABLE;
    }
}

From source file:com.viettel.logistic.wms.dao.SerialInventoryDAO.java

public ResultDTO insertListSerialInventoryBatch(List<SerialInventoryDTO> lstSerialInventoryDTO,
        Connection connection) {/*  w w  w . ja  v  a  2  s .  co  m*/
    ResultDTO resultDTO = new ResultDTO();
    //connection.
    //PREPARE STATEMENTS
    PreparedStatement prstmtInsertSerialInventory;
    //SQL
    StringBuilder sqlSerialInventory = new StringBuilder();

    int numberNeedToCommit = 0;
    int numberOfSuccess = 0;
    int numberOfFail = 0;
    //
    List paramsSerialInventory;
    //mac dinh la thanh cong
    resultDTO.setMessage(ParamUtils.SUCCESS);
    try {
        //1.KHOI TAO SESSION
        //2.1 TAO STATEMENTS SERIAL_INVENTORY
        sqlSerialInventory.append(" INSERT INTO serial_inventory(id, cust_id, cust_code, cust_name, stock_id,");
        sqlSerialInventory.append("       goods_id, goods_code, goods_name, goods_state,");
        sqlSerialInventory.append("       quantity, from_serial, to_serial, cell_code, barcode,");
        sqlSerialInventory.append(
                "       create_date, note, status, staff_id, staff_code,staff_name, inventory_code, goods_unit_type_name) ");
        sqlSerialInventory.append(
                " VALUES (SERIAL_INVENTORY_SEQ.nextval, TO_NUMBER(?), ?, ?, TO_NUMBER(?), TO_NUMBER(?), ");
        sqlSerialInventory.append(
                "  ?, ?, ?, TO_NUMBER(?), ?, ?, ?, ?, TO_DATE(?,'dd/MM/yyyy hh24:mi:ss'), ?, TO_NUMBER(?), ");
        sqlSerialInventory.append("  TO_NUMBER(?), ?, ?, ?, ? ) ");
        sqlSerialInventory.append(" LOG ERRORS REJECT LIMIT UNLIMITED ");
        //3. TAO PREPARE STATEMENT
        prstmtInsertSerialInventory = connection.prepareStatement(sqlSerialInventory.toString());
        //Chi tiet serial  
        for (SerialInventoryDTO serialInventoryDTO : lstSerialInventoryDTO) {
            numberNeedToCommit++;
            //SET PARAMS FOR SERIAL_INVENTORY
            paramsSerialInventory = setParamsSerialInventory(serialInventoryDTO);
            //SET PARAMS AND ADD TO BATCH
            for (int idx = 0; idx < paramsSerialInventory.size(); idx++) {
                prstmtInsertSerialInventory.setString(idx + 1,
                        DataUtil.nvl(paramsSerialInventory.get(idx), "").toString());
            }
            prstmtInsertSerialInventory.addBatch();

            if (numberNeedToCommit >= Constants.COMMIT_NUM) {
                try {
                    prstmtInsertSerialInventory.executeBatch();
                    numberOfSuccess = numberOfSuccess + numberNeedToCommit;
                } catch (Exception ex) {
                    numberOfFail = numberOfFail + numberNeedToCommit;
                }
                numberNeedToCommit = 0;
            }
        } //END FOR
        if (numberNeedToCommit > 0) {
            try {
                prstmtInsertSerialInventory.executeBatch();
                numberOfSuccess += numberNeedToCommit;
            } catch (Exception ex) {
                //connection.rollback();
                numberOfFail += numberNeedToCommit;
            }
        }
        prstmtInsertSerialInventory.close();
    } catch (SQLException | NumberFormatException e) {
        Logger.getLogger(StockGoodsSerialDAO.class.getName()).log(Level.SEVERE, null, e);
        resultDTO.setMessage(ParamUtils.FAIL);
    }

    //lay so luong hang hoa insert vao ban err$_
    List<StockGoodsSerialInforDTO> lstError = getListErrorSerialInventory(
            lstSerialInventoryDTO.get(0).getInventoryCode());
    int amountError = 0;
    if (lstError != null) {
        amountError = lstError.size();
    }
    int amountTotal = lstSerialInventoryDTO.size();
    numberOfSuccess = amountTotal - amountError;//So luong ban ghi insert thanh cong
    numberOfFail = amountError;//so luong hang loi da ton tai serial cua khach hang trong ban kiem ke
    //
    resultDTO.setQuantityFail(numberOfFail);
    resultDTO.setQuantitySucc(numberOfSuccess);
    resultDTO.setLstStockGoodsSerialInforDTO(lstError);
    // tra ve list serial loi
    return resultDTO;
}

From source file:com.nextep.designer.dbgm.services.impl.DataService.java

@Override
public void addDataline(IDataSet set, IDataLine... lines) {
    Connection localConn = null;/*from   w  w w.  j  a v  a 2  s  .  c  om*/
    PreparedStatement stmt = null;
    IStorageHandle handle = set.getStorageHandle();
    if (handle == null) {
        storageService.createDataSetStorage(set);
        handle = set.getStorageHandle();
    }
    try {
        localConn = storageService.getLocalConnection();
        final String insertStmt = handle.getInsertStatement();
        stmt = localConn.prepareStatement(insertStmt);
        for (IDataLine line : lines) {
            int col = 1;
            // For repository handles, we specify the row id
            // if (handle.isRepositoryHandle()) {
            if (line.getRowId() == 0) {
                stmt.setNull(col++, Types.BIGINT);
            } else {
                stmt.setLong(col++, line.getRowId());
            }
            // }
            // Processing line data
            for (IReference r : set.getColumnsRef()) {
                final IColumnValue value = line.getColumnValue(r);
                Object valueObj = null;
                if (value != null) {
                    valueObj = value.getValue();
                    if (valueObj != null) {
                        stmt.setObject(col, valueObj);
                    } else {
                        IBasicColumn c = (IBasicColumn) VersionHelper.getReferencedItem(r);
                        int jdbcType = storageService.getColumnSqlType(set, c);
                        stmt.setNull(col, jdbcType);
                    }
                }
                // Incrementing column index
                col++;

            }
            stmt.addBatch();
        }
        stmt.executeBatch();
        localConn.commit();
    } catch (SQLException e) {
        LOGGER.error(DBGMMessages.getString("service.data.addDatalineFailed") + e.getMessage(), //$NON-NLS-1$
                e);
    } finally {
        safeClose(null, stmt, localConn, false);
    }

}

From source file:fr.aliacom.obm.common.contact.ContactDaoJdbcImpl.java

private PreparedStatement insertAddresses(Connection con, EntityId entityId, Map<String, Address> addresses)
        throws SQLException {
    PreparedStatement ps;
    ps = con.prepareStatement("INSERT INTO Address (address_entity_id, address_label, "
            + "address_street, address_zipcode, address_town,"
            + "address_expresspostal, address_country, address_state) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    for (Entry<String, Address> entry : addresses.entrySet()) {
        Address ad = entry.getValue();//from w  w w . j  ava  2  s .c o  m
        ps.setInt(1, entityId.getId());
        ps.setString(2, entry.getKey());
        ps.setString(3, ad.getStreet());
        ps.setString(4, ad.getZipCode());
        ps.setString(5, ad.getTown());
        ps.setString(6, ad.getExpressPostal());
        ps.setString(7, getCountryIso3166(con, ad.getCountry()));
        ps.setString(8, ad.getState());
        ps.addBatch();
    }
    ps.executeBatch();
    return ps;
}

From source file:org.wso2.carbon.policy.mgt.core.dao.impl.PolicyDAOImpl.java

@Override
public Policy addPolicyToRole(List<String> rolesToAdd, Policy policy) throws PolicyManagerDAOException {
    Connection conn;//  w ww .  java 2  s.co m
    PreparedStatement insertStmt = null;
    //        PreparedStatement deleteStmt = null;
    //        final List<String> currentRoles = this.getPolicy(policy.getId()).getRoles();
    //
    //        SetReferenceTransformer<String> transformer = new SetReferenceTransformer<String>();
    //
    //        transformer.transform(currentRoles, rolesToAdd);
    //        rolesToAdd = transformer.getObjectsToAdd();
    //        List<String> rolesToDelete = transformer.getObjectsToRemove();
    try {
        conn = this.getConnection();
        if (rolesToAdd.size() > 0) {
            String query = "INSERT INTO DM_ROLE_POLICY (ROLE_NAME, POLICY_ID) VALUES (?, ?)";
            insertStmt = conn.prepareStatement(query);
            for (String role : rolesToAdd) {
                insertStmt.setString(1, role);
                insertStmt.setInt(2, policy.getId());
                insertStmt.addBatch();
            }
            insertStmt.executeBatch();
        }
        //            if (rolesToDelete.size() > 0){
        //                String deleteQuery = "DELETE FROM DM_ROLE_POLICY WHERE ROLE_NAME=? AND POLICY_ID=?";
        //                deleteStmt = conn.prepareStatement(deleteQuery);
        //                for (String role : rolesToDelete) {
        //                    deleteStmt.setString(1, role);
        //                    deleteStmt.setInt(2, policy.getId());
        //                    deleteStmt.addBatch();
        //                }
        //                deleteStmt.executeBatch();
        //            }
    } catch (SQLException e) {
        throw new PolicyManagerDAOException("Error occurred while adding the role name with policy to database",
                e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(insertStmt, null);
    }
    return policy;
}

From source file:org.freebxml.omar.server.persistence.rdb.SlotDAO.java

/**
 * @param parentInsert It should be set to true if Slot insert is part of new
 * RegistryObject insert (i.e. in the case        of SubmitObjectsRequest). It should
 * be set to false in the case of AddSlotsRequest because the parent of the
 * slot is expected to be already submitted by previous SubmitObjectRequest.
 * In the latter case whether the parents of the slots exist will be checked.
 *//*from ww  w .  ja va  2 s.  co  m*/
public void insert(List slots, boolean parentInsert) throws RegistryException {
    PreparedStatement pstmt = null;

    String parentId = (String) parent;

    if (slots.size() == 0) {
        return;
    }

    try {
        String sql = "INSERT INTO " + getTableName() + " (sequenceId, " + "name_, slotType, value, parent)"
                + " VALUES(?, ?, ?, ?, ?)";
        pstmt = context.getConnection().prepareStatement(sql);

        List duplicateSlotsNames = getDuplicateSlots(slots);

        if (duplicateSlotsNames.size() > 0) {
            // Some slots have duplicate name
            throw new DuplicateSlotsException(parentId, duplicateSlotsNames);
        }

        RegistryObjectDAO roDAO = new RegistryObjectDAO(context);

        // Check whether the parent exist in database, in case the parent
        // has been inserted by the previous SubmitObjectsRequest
        // (i.e. in the case of AddSlotsRequest)
        if (!parentInsert && !roDAO.registryObjectExist(parentId)) {
            // The parent does not exist
            throw new SlotsParentNotExistException(parentId);
        }
        /* HIEOS/BHT: Disabled for performance purposes.
        List slotsNamesAlreadyExist = slotsExist(parentId, slots);
                
        if (slotsNamesAlreadyExist.size() > 0) {
        // Some slots for this RegistryObject already exist
        throw new SlotsExistException(parentId, slotsNamesAlreadyExist);
        }*/

        Iterator iter = slots.iterator();
        Vector slotNames = new Vector();

        while (iter.hasNext()) {
            Slot slot = (Slot) iter.next();
            String slotName = slot.getName();
            String slotType = slot.getSlotType();
            List values = slot.getValueList().getValue();
            int size = values.size();

            for (int j = 0; j < size; j++) {
                String value = ((Value) values.get(j)).getValue();
                pstmt.setInt(1, j);
                pstmt.setString(2, slotName);
                pstmt.setString(3, slotType);
                pstmt.setString(4, value);
                pstmt.setString(5, parentId);
                log.trace("SQL = " + sql); // HIEOS/BHT: DEBUG (fix)
                pstmt.addBatch();
            }
        }

        if (slots.size() > 0) {
            int[] updateCounts = pstmt.executeBatch();
        }
    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } finally {
        closeStatement(pstmt);
    }
}

From source file:org.wso2.carbon.policy.mgt.core.dao.impl.PolicyDAOImpl.java

@Override
public Policy addPolicyToUser(List<String> usersToAdd, Policy policy) throws PolicyManagerDAOException {
    Connection conn;/*from  w  ww.j av  a 2  s .c  om*/
    PreparedStatement insertStmt = null;
    //        PreparedStatement deleteStmt = null;
    //        final List<String> currentUsers = this.getPolicy(policy.getId()).getUsers();
    //
    //        SetReferenceTransformer<String> transformer = new SetReferenceTransformer<String>();
    //
    //        transformer.transform(currentUsers, usersToAdd);
    //        usersToAdd = transformer.getObjectsToAdd();
    //        List<String> usersToDelete = transformer.getObjectsToRemove();
    try {
        conn = this.getConnection();
        if (usersToAdd.size() > 0) {
            String query = "INSERT INTO DM_USER_POLICY (POLICY_ID, USERNAME) VALUES (?, ?)";
            insertStmt = conn.prepareStatement(query);
            for (String username : usersToAdd) {
                insertStmt.setInt(1, policy.getId());
                insertStmt.setString(2, username);
                insertStmt.addBatch();
            }
            insertStmt.executeBatch();
        }
        //            if (usersToDelete.size() > 0){
        //                String deleteQuery = "DELETE FROM DM_USER_POLICY WHERE USERNAME=? AND POLICY_ID=?";
        //                deleteStmt = conn.prepareStatement(deleteQuery);
        //                for (String username : usersToDelete) {
        //                    deleteStmt.setString(1, username);
        //                    deleteStmt.setInt(2, policy.getId());
        //                    deleteStmt.addBatch();
        //                }
        //                deleteStmt.executeBatch();
        //            }

    } catch (SQLException e) {
        throw new PolicyManagerDAOException("Error occurred while adding the user name with policy to database",
                e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(insertStmt, null);
        //            PolicyManagementDAOUtil.cleanupResources(deleteStmt, null);
    }
    return policy;
}