Example usage for org.springframework.jdbc.core.namedparam MapSqlParameterSource MapSqlParameterSource

List of usage examples for org.springframework.jdbc.core.namedparam MapSqlParameterSource MapSqlParameterSource

Introduction

In this page you can find the example usage for org.springframework.jdbc.core.namedparam MapSqlParameterSource MapSqlParameterSource.

Prototype

public MapSqlParameterSource() 

Source Link

Document

Create an empty MapSqlParameterSource, with values to be added via addValue .

Usage

From source file:org.tradex.jdbc.JDBCHelper.java

/**
 * Generates a SqlParameterSource for the passed SQL text and supplied binds
 * @param sql The SQL to bind to/*from   w  w w.j  a  v  a 2  s. c  o  m*/
 * @param binds The supplied variables to bind
 * @return a SqlParameterSource
 */
public SqlParameterSource getBinds(String sql, final Object... binds) {
    final MapSqlParameterSource sqlParamSource = new MapSqlParameterSource();
    int[] parameterTypes = TYPE_CACHE.get(sql);
    if (parameterTypes == null) {
        synchronized (TYPE_CACHE) {
            parameterTypes = TYPE_CACHE.get(sql);
            if (parameterTypes == null) {
                Connection conn = null;
                PreparedStatement ps = null;
                try {
                    conn = ds.getConnection();
                    ps = conn.prepareStatement(NamedParameterUtils.parseSqlStatementIntoString(sql).toString());
                    ParameterMetaData pmd = ps.getParameterMetaData();
                    int paramCount = pmd.getParameterCount();
                    if (paramCount > 0 && (binds == null || binds.length != paramCount)) {
                        throw new RuntimeException("Bind Count [" + (binds == null ? 0 : binds.length)
                                + "] was not equal to parameter count [" + paramCount + "]");
                    }
                    parameterTypes = new int[paramCount];
                    for (int i = 0; i < paramCount; i++) {
                        parameterTypes[i] = pmd.getParameterType(i + 1);
                    }
                } catch (RuntimeException re) {
                    throw re;
                } catch (Exception e) {
                    throw new RuntimeException("Failed to get binds for [" + sql + "]", e);
                } finally {
                    try {
                        ps.close();
                    } catch (Exception e) {
                    }
                    try {
                        conn.close();
                    } catch (Exception e) {
                    }
                }

            }
            TYPE_CACHE.put(sql, parameterTypes);
        }
    }
    for (int i = 0; i < parameterTypes.length; i++) {
        sqlParamSource.addValue("" + i, binds[i], parameterTypes[i]);
    }
    return sqlParamSource;
}

From source file:com.ushahidi.swiftriver.core.api.service.DropIndexService.java

/**
 * Returns a <code>java.util.Map</code> that contains a list of
 * all [latitude, longitude] pairs for the place entities associated
 * with each of the {@link Drop} entities in the <code>drops</code>
 * parameter//from w w  w. java  2s  . c  om
 *  
 * @param drops
 * @return
 */
private Map<Long, List<String>> getDropPlaces(List<Drop> drops) {
    Map<Long, List<String>> dropPlaces = new HashMap<Long, List<String>>();

    // Fetch the drop ids
    List<Long> dropIds = new ArrayList<Long>();
    for (Drop drop : drops) {
        dropIds.add(drop.getId());
    }

    // Query to fetch the places associated with the drops 
    String sql = "SELECT droplets_places.droplet_id, " + "places.longitude, places.latitude " + "FROM places "
            + "INNER JOIN droplets_places ON (droplets_places.place_id = places.id) "
            + "WHERE droplets_places.droplet_id IN (:dropIds)";

    MapSqlParameterSource paramMap = new MapSqlParameterSource();
    paramMap.addValue("dropIds", dropIds);

    for (Map<String, Object> row : namedJdbcTemplate.queryForList(sql, paramMap)) {
        Long dropId = ((Number) row.get("droplet_id")).longValue();

        Float longitude = ((Number) row.get("longitude")).floatValue();
        Float latitude = ((Number) row.get("latitude")).floatValue();

        List<String> places = dropPlaces.get(dropId);
        if (places == null) {
            places = new ArrayList<String>();
        }

        places.add(String.format("%s,%s", latitude, longitude));
        dropPlaces.put(dropId, places);
    }

    return dropPlaces;
}

From source file:com.team3637.service.MatchServiceMySQLImpl.java

@Override
public void mergeTags(String oldTag, String newTag) {
    SqlParameterSource args = new MapSqlParameterSource().addValue("tableName", "matches")
            .addValue("noTagCols", 4).addValue("oldTag", oldTag).addValue("newTag", newTag);
    mergeTags.execute(args);//from  w ww . java 2 s .  c  o  m
}

From source file:me.ronghai.sa.dao.impl.AbstractModelDAOWithJDBCImpl.java

@Override
public int remove(boolean force, Collection<Long> ids, String configure) {
    if (ids == null || ids.isEmpty()) {
        return 0;
    }//from ww w .  ja  v a  2  s. c om
    this.beforeRemove(force, ids, configure);
    String sql;
    String table = table(entityClass);
    if (force) {
        sql = "DELETE FROM " + table + "  e  WHERE id IN (:ids) ";
    } else {
        sql = "UPDATE " + table + "  SET disabled = 1  WHERE id IN (:ids) ";
    }
    if (StringUtils.isNotEmpty(configure)) {
        if (!configure.trim().toUpperCase().startsWith("AND")) {
            sql += " AND  ";
        }
        sql += configure;
    }
    logger.info("remove ids " + ids);
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("ids", new ArrayList<>(ids));
    int n = this.databaseHandler.update(sql, parameters);

    this.afterRemove(force, ids, configure);
    return n;

}

From source file:org.owasp.proxy.http.dao.JdbcMessageDAO.java

public boolean deleteConversation(int id) throws DataAccessException {
    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue(ID, id, Types.INTEGER);
    return getNamedParameterJdbcTemplate().update(DELETE_CONVERSATION, params) > 0;
}

From source file:com.joliciel.frenchTreebank.TreebankDaoImpl.java

public void savePhrase(PhraseInternal phrase) {
    NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(this.getDataSource());
    MapSqlParameterSource paramSource = new MapSqlParameterSource();
    paramSource.addValue("phrase_ptype_id", phrase.getPhraseTypeId() == 0 ? null : phrase.getPhraseTypeId());
    paramSource.addValue("phrase_parent_id", phrase.getParent() == null ? null : phrase.getParent().getId());
    paramSource.addValue("phrase_function_id", phrase.getFunctionId() == 0 ? null : phrase.getFunctionId());
    paramSource.addValue("phrase_position", phrase.getPositionInPhrase());
    paramSource.addValue("phrase_depth", phrase.getDepth());

    if (phrase.isNew()) {
        String sql = "SELECT nextval('ftb_phrase_phrase_id_seq')";
        LOG.info(sql);//www. j a  va2 s.  c  o m
        int phraseId = jt.queryForInt(sql, paramSource);
        paramSource.addValue("phrase_id", phraseId);

        sql = "INSERT INTO ftb_phrase (phrase_id, phrase_ptype_id, phrase_parent_id, phrase_function_id, phrase_position, phrase_depth) "
                + "VALUES (:phrase_id, :phrase_ptype_id, :phrase_parent_id, :phrase_function_id, :phrase_position, :phrase_depth)";

        LOG.info(sql);
        TreebankDaoImpl.LogParameters(paramSource);
        jt.update(sql, paramSource);

        phrase.setId(phraseId);
    }
}

From source file:com.joliciel.lefff.LefffDaoImpl.java

public Category loadCategory(int categoryId) {
    NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(this.getDataSource());
    String sql = "SELECT " + SELECT_CATEGORY + " FROM lef_category WHERE category_id=:category_id";
    MapSqlParameterSource paramSource = new MapSqlParameterSource();
    paramSource.addValue("category_id", categoryId);

    LOG.info(sql);/*w w  w  .j  a va 2  s  . co m*/
    LefffDaoImpl.LogParameters(paramSource);
    Category category = null;
    try {
        category = (Category) jt.queryForObject(sql, paramSource,
                new CategoryMapper(this.getLefffServiceInternal()));
    } catch (EmptyResultDataAccessException ex) {
        ex.hashCode();
    }
    return category;
}

From source file:com.epam.catgenome.dao.BiologicalDataItemDao.java

/**
 * Finds files with names matching a specified file name, performs substring, case insensitive search
 * @param name search query//from ww w  .j  av  a2  s  .  c  o m
 * @return {@code List} of files with a matching name
 */
@Transactional(propagation = Propagation.MANDATORY)
public List<BiologicalDataItem> loadFilesByName(final String name) {
    final MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue(BiologicalDataItemParameters.NAME.name(), "%" + name.toLowerCase() + "%");
    return getNamedParameterJdbcTemplate().query(loadBiologicalDataItemsByNameQuery, params, getRowMapper());
}

From source file:com.epam.catgenome.dao.DaoHelper.java

/**
 * Creates a new temporary list of {@code Long} values. The created temporary list is
 * identified by the given ID. If a list has been created successfully, it will be filled
 * in by {@code Collection} of provided {@code Long} values.
 *
 * @param listId {@code Long} represents unique ID that is used to identify a temporary list
 * @param list   {@code Collection} specifies collection of {@code Long} values that should be
 *               associated with a temporary list if this call is succeeded
 * @return {@code Long} represents unique ID of a temporary list that has been created after
 * this call//from  www  .  j  av  a  2 s  .  c  om
 * @throws IllegalArgumentException will be thrown if <tt>listId</tt> or <tt>list</tt> are
 *                                  <tt>null</tt>, or the given <tt>list</tt> is empty
 */
@Transactional(propagation = Propagation.MANDATORY)
public Long createTempLongList(final Long listId, final Collection<Long> list) {
    Assert.notNull(listId);
    Assert.isTrue(CollectionUtils.isNotEmpty(list));
    // creates a new local temporary table if it doesn't exists to handle temporary lists
    getJdbcTemplate().update(createTemporaryListQuery);
    // fills in a temporary list by given values
    int i = 0;
    final Iterator<Long> iterator = list.iterator();
    final MapSqlParameterSource[] batchArgs = new MapSqlParameterSource[list.size()];
    while (iterator.hasNext()) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue(HelperParameters.LIST_ID.name(), listId);
        params.addValue(HelperParameters.LIST_VALUE.name(), iterator.next());
        batchArgs[i] = params;
        i++;
    }
    getNamedParameterJdbcTemplate().batchUpdate(insertTemporaryListItemQuery, batchArgs);
    return listId;
}

From source file:com.joliciel.jochre.security.SecurityDaoJdbc.java

@Override
public void saveParametersInternal(ParametersInternal parameters) {
    NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(this.getDataSource());
    MapSqlParameterSource paramSource = new MapSqlParameterSource();

    paramSource.addValue("param_last_failed_login", parameters.getLastFailedLoginAttempt());
    paramSource.addValue("param_captcha_interval", parameters.getCaptachaIntervalSeconds());
    String sql = null;/*from   w w  w.j av a  2  s  .c  o  m*/

    paramSource.addValue("param_id", parameters.getId());

    sql = "UPDATE ocr_param" + " SET param_last_failed_login = :param_last_failed_login"
            + ", param_captcha_interval = :param_captcha_interval" + " WHERE param_id = :param_id";

    LOG.info(sql);
    logParameters(paramSource);
    jt.update(sql, paramSource);

}