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

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

Introduction

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

Prototype

public MapSqlParameterSource addValue(String paramName, @Nullable Object value) 

Source Link

Document

Add a parameter to this parameter source.

Usage

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 ww  w .  j a v a 2s . com
 *  
 * @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.qualogy.qafe.business.resource.rdb.query.QueryToStringCreator.java

/**
 * @param userOperator/*from w ww.  j a v a2 s  .c o  m*/
 * @param userFilledValue
 * @param columnName
 * @param namedParameters
 * @return
 */
private static String generateConditionForUserFilledValue(boolean isReverseCondition, String userOperator,
        String userFilledValue, String columnName, MapSqlParameterSource namedParameters) {
    String sql = "";
    if (isLikeOperator(userOperator)) {
        sql = replaceUserOperatorInLikeSqlStatement(isReverseCondition, columnName, userFilledValue);
    } else if (userOperator.equals("NULL")) {
        sql = replaceUserOperatorInNULLSqlStatement(isReverseCondition, columnName);
    } else if (userOperator.equals("IN")) {
        sql = replaceUserOperatorInINSqlStatement(columnName, userFilledValue);
    } else if (userOperator.equals("NOT")) {
        sql = replaceUserOperatorInNOTSqlStatement(columnName, userFilledValue, namedParameters);
    } else if (userOperator.equals("BETWEEN")) {
        sql = replaceUserOperatorInBetweenSqlStatement(columnName, userFilledValue);
    } else {
        String userFilledValueWithoutOperator = StringUtils.remove(userFilledValue, userOperator);
        namedParameters.addValue(columnName, userFilledValueWithoutOperator);

        sql += (columnName + userOperator + ":" + columnName);
    }
    sql = removeFromEnd(sql, "AND");
    sql += " AND ";
    return sql;
}

From source file:com.ushahidi.swiftriver.core.api.dao.impl.JpaTagDao.java

/**
 * Populate the droplet tags table.// w w  w  .j a  va 2 s.com
 * 
 * @param drops
 */
private void insertDropletTags(List<Drop> drops) {

    // List of drop IDs in the drops list
    List<Long> dropIds = new ArrayList<Long>();
    // List of tags in a drop
    Map<Long, Set<Long>> dropletTagsMap = new HashMap<Long, Set<Long>>();
    for (Drop drop : drops) {

        if (drop.getTags() == null)
            continue;

        dropIds.add(drop.getId());

        for (Tag tag : drop.getTags()) {
            Set<Long> tags = null;
            if (dropletTagsMap.containsKey(drop.getId())) {
                tags = dropletTagsMap.get(drop.getId());
            } else {
                tags = new HashSet<Long>();
                dropletTagsMap.put(drop.getId(), tags);
            }

            tags.add(tag.getId());
        }
    }

    // Find droplet tags that already exist in the db
    String sql = "SELECT droplet_id, tag_id FROM droplets_tags WHERE droplet_id in (:ids)";

    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue("ids", dropIds);

    List<Map<String, Object>> results = this.namedJdbcTemplate.queryForList(sql, params);

    // Remove already existing droplet_tags from our Set
    for (Map<String, Object> result : results) {
        long dropletId = ((Number) result.get("droplet_id")).longValue();
        long tagId = ((Number) result.get("tag_id")).longValue();

        Set<Long> tagSet = dropletTagsMap.get(dropletId);
        if (tagSet != null) {
            tagSet.remove(tagId);
        }
    }

    // Insert the remaining items in the set into the db
    sql = "INSERT INTO droplets_tags (droplet_id, tag_id) VALUES (?,?)";

    final List<long[]> dropletTagsList = new ArrayList<long[]>();
    for (Long dropletId : dropletTagsMap.keySet()) {
        for (Long tagId : dropletTagsMap.get(dropletId)) {
            long[] dropletTag = { dropletId, tagId };
            dropletTagsList.add(dropletTag);
        }
    }
    jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            long[] dropletTag = dropletTagsList.get(i);
            ps.setLong(1, dropletTag[0]);
            ps.setLong(2, dropletTag[1]);
        }

        public int getBatchSize() {
            return dropletTagsList.size();
        }
    });
}

From source file:com.ushahidi.swiftriver.core.api.dao.impl.JpaPlaceDao.java

/**
 * Populate the droplet places table./*from w w  w .  j  a  va2 s  .c  o m*/
 * 
 * @param drops
 */
private void insertDropletPlaces(List<Drop> drops) {

    // List of drop IDs in the drops list
    List<Long> dropIds = new ArrayList<Long>();
    // List of places in a drop
    Map<Long, Set<Long>> dropletPlacesMap = new HashMap<Long, Set<Long>>();
    for (Drop drop : drops) {

        if (drop.getPlaces() == null)
            continue;

        dropIds.add(drop.getId());

        for (Place place : drop.getPlaces()) {
            Set<Long> places = null;
            if (dropletPlacesMap.containsKey(drop.getId())) {
                places = dropletPlacesMap.get(drop.getId());
            } else {
                places = new HashSet<Long>();
                dropletPlacesMap.put(drop.getId(), places);
            }

            places.add(place.getId());
        }
    }

    // Find droplet places that already exist in the db
    String sql = "SELECT droplet_id, place_id FROM droplets_places WHERE droplet_id in (:ids)";

    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue("ids", dropIds);

    List<Map<String, Object>> results = this.namedJdbcTemplate.queryForList(sql, params);

    // Remove already existing droplet_places from our Set
    for (Map<String, Object> result : results) {
        long dropletId = ((Number) result.get("droplet_id")).longValue();
        long placeId = ((Number) result.get("place_id")).longValue();

        Set<Long> placeSet = dropletPlacesMap.get(dropletId);
        if (placeSet != null) {
            placeSet.remove(placeId);
        }
    }

    // Insert the remaining items in the set into the db
    sql = "INSERT INTO droplets_places (droplet_id, place_id) VALUES (?,?)";

    final List<long[]> dropletPlacesList = new ArrayList<long[]>();
    for (Long dropletId : dropletPlacesMap.keySet()) {
        for (Long placeId : dropletPlacesMap.get(dropletId)) {
            long[] dropletPlace = { dropletId, placeId };
            dropletPlacesList.add(dropletPlace);
        }
    }
    jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            long[] dropletPlace = dropletPlacesList.get(i);
            ps.setLong(1, dropletPlace[0]);
            ps.setLong(2, dropletPlace[1]);
        }

        public int getBatchSize() {
            return dropletPlacesList.size();
        }
    });
}

From source file:com.ushahidi.swiftriver.core.api.dao.impl.JpaLinkDao.java

/**
 * Populate the droplet links table.//from   ww w .j  a  v  a 2 s  .  co  m
 * 
 * @param drops
 */
private void insertDropletLinks(List<Drop> drops) {

    // List of drop IDs in the drops list
    List<Long> dropIds = new ArrayList<Long>();
    // List of links in a drop
    Map<Long, Set<Long>> dropletLinksMap = new HashMap<Long, Set<Long>>();
    // List of drops and the link that is their original url
    final List<long[]> originalUrls = new ArrayList<long[]>();
    for (Drop drop : drops) {

        if (drop.getLinks() == null)
            continue;

        dropIds.add(drop.getId());

        for (Link link : drop.getLinks()) {
            Set<Long> links = null;
            if (dropletLinksMap.containsKey(drop.getId())) {
                links = dropletLinksMap.get(drop.getId());
            } else {
                links = new HashSet<Long>();
                dropletLinksMap.put(drop.getId(), links);
            }

            // Is this link the original url?
            if (drop.getOriginalUrl() != null && link.getUrl().equals(drop.getOriginalUrl().getUrl())) {
                long[] originalUrl = { drop.getId(), link.getId() };
                originalUrls.add(originalUrl);
            }

            links.add(link.getId());
        }
    }

    // Find droplet links that already exist in the db
    String sql = "SELECT droplet_id, link_id FROM droplets_links WHERE droplet_id in (:ids)";

    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue("ids", dropIds);

    List<Map<String, Object>> results = this.namedJdbcTemplate.queryForList(sql, params);

    // Remove already existing droplet_links from our Set
    for (Map<String, Object> result : results) {
        long dropletId = ((Number) result.get("droplet_id")).longValue();
        long linkId = ((Number) result.get("link_id")).longValue();

        Set<Long> linkSet = dropletLinksMap.get(dropletId);
        if (linkSet != null) {
            linkSet.remove(linkId);
        }
    }

    // Insert the remaining items in the set into the db
    sql = "INSERT INTO droplets_links (droplet_id, link_id) VALUES (?,?)";

    final List<long[]> dropletLinksList = new ArrayList<long[]>();
    for (Long dropletId : dropletLinksMap.keySet()) {
        for (Long linkId : dropletLinksMap.get(dropletId)) {
            long[] dropletLink = { dropletId, linkId };
            dropletLinksList.add(dropletLink);
        }
    }
    jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            long[] dropletLink = dropletLinksList.get(i);
            ps.setLong(1, dropletLink[0]);
            ps.setLong(2, dropletLink[1]);
        }

        public int getBatchSize() {
            return dropletLinksList.size();
        }
    });

    if (originalUrls.size() > 0) {
        sql = "UPDATE droplets SET original_url = ? WHERE id = ?";
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                long[] update = originalUrls.get(i);
                ps.setLong(1, update[1]);
                ps.setLong(2, update[0]);
            }

            public int getBatchSize() {
                return originalUrls.size();
            }
        });
    }
}

From source file:org.inbio.modeling.core.dao.impl.SystemUserDAOImpl.java

@Override
public void createUser(SystemUser newUser) {
    String createStatement = null;
    MapSqlParameterSource args = null;

    try {/* w w  w.  ja v a 2  s.c  o  m*/
        createStatement = "INSERT INTO " + this.table + " ( fullname, username, \"password\", enabled, roles)"
                + "VALUES (:fullname, :username, :passwd, :enabled, :roles) ";

        args = new MapSqlParameterSource();
        args.addValue("fullname", newUser.getFullname());
        args.addValue("username", newUser.getUsername());
        args.addValue("passwd", newUser.getPassword());
        args.addValue("enabled", newUser.isEnabled());
        args.addValue("roles", newUser.getRoles());

        getSimpleJdbcTemplate().update(createStatement, args);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.terasoluna.gfw.tutorial.selenium.DBLogAssertOperations.java

/**
 * ???(??)???????/*from w ww  . j ava  2s.co m*/
 * @param stackTracePattern ?()
 */
public void assertContainsByRegexStackTrace(String stackTracePattern) {

    StringBuilder sql = new StringBuilder();
    StringBuilder where = new StringBuilder();
    sql.append("SELECT COUNT(e.*) FROM logging_event_exception e");
    where.append(" WHERE e.TRACE_LINE REGEXP :stackTrace");
    sql.append(where);

    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue("stackTrace", stackTracePattern);
    Long count = jdbcOperations.queryForObject(sql.toString(), params, Long.class);
    assertThat(count, is(1L));
}

From source file:org.inbio.modeling.core.dao.impl.SystemUserDAOImpl.java

@Override
public void updateUser(SystemUser user) {
    String sqlStatement = null;/*from  w w  w  .j  a  v  a2  s  .c om*/
    MapSqlParameterSource args = null;

    try {
        sqlStatement = "UPDATE " + this.table + " SET fullname = :fullname" + ", password = :passwd"
                + ", enabled = :enabled" + ", roles = :roles" + " WHERE username = :username ";

        args = new MapSqlParameterSource();
        args.addValue("username", user.getUsername());
        args.addValue("fullname", user.getFullname());
        args.addValue("passwd", user.getPassword());
        args.addValue("enabled", user.isEnabled());
        args.addValue("roles", user.getRoles());

        getSimpleJdbcTemplate().update(sqlStatement, args);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.terasoluna.gfw.tutorial.selenium.DBLogAssertOperations.java

private long getCountInLogContainsByMessage(String xTrack, String loggerName, String message) {
    StringBuilder sql = new StringBuilder();
    StringBuilder where = new StringBuilder();
    sql.append("SELECT COUNT(*) FROM logging_event e");
    where.append(" WHERE e.formatted_message = :message");
    if (StringUtils.hasText(xTrack)) {
        sql.append("JOIN logging_event_property ep ON ep.event_id = e.event_id AND ep.mapped");
        where.append(" AND ep.mapped_key = 'X-Track' AND ep.mapped_value = :xTrack");
    }/*from w  ww  . ja  v a2  s. c o m*/
    if (StringUtils.hasText(loggerName)) {
        where.append(" AND e.logger_name = :loggerName");
    }
    sql.append(where);

    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue("xTrack", xTrack);
    params.addValue("loggerName", loggerName);
    params.addValue("message", message);
    return jdbcOperations.queryForObject(sql.toString(), params, Long.class);
}

From source file:fr.acxio.tools.agia.item.database.AbstractFieldSetSqlParameterSourceProvider.java

protected MapSqlParameterSource mapFieldSet(MapSqlParameterSource sMapSqlParameterSource, FieldSet sFieldSet,
        int sRecIdx) {
    if (sFieldSet != null) {
        boolean aHasNames = sFieldSet.hasNames();
        int aFieldCount = sFieldSet.getFieldCount();
        String[] aNames = aHasNames ? sFieldSet.getNames() : null;
        String[] aValues = sFieldSet.getValues();
        for (int i = 0; i < aFieldCount; i++) {
            sMapSqlParameterSource.addValue(String.format(fieldsetNameFormat, sRecIdx,
                    (aHasNames && (aNames[i] != null) && !aNames[i].isEmpty()) ? aNames[i]
                            : String.format(unnamedColumnFormat, i)),
                    aValues[i]);/*from w w w.j  av a  2  s . co  m*/
        }
    }
    return sMapSqlParameterSource;
}