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:com.ushahidi.swiftriver.core.api.dao.impl.JpaIdentityDao.java

/**
 * For the given list of new drops, find those that the identity hash
 * already exists in the db and update the drop entry with the existing id.
 * Also remove the hash from the new identity index.
 * /*from   w ww . j a  v  a  2 s .  c om*/
 * @param newIdentityIndex
 * @param drops
 */
private void updateNewIdentityIndex(Map<String, List<Integer>> newIdentityIndex, List<Drop> drops) {
    // First find and update existing drops with their ids.
    String sql = "SELECT id, hash FROM identities WHERE hash IN (:hashes)";

    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue("hashes", newIdentityIndex.keySet());

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

    // Update id for the drops that were found
    for (Map<String, Object> result : results) {
        String hash = (String) result.get("hash");
        Long id = ((BigInteger) result.get("id")).longValue();

        List<Integer> indexes = newIdentityIndex.get(hash);
        for (Integer index : indexes) {
            drops.get(index).getIdentity().setId(id);
        }

        // Hash is not for a new drop so remove it
        newIdentityIndex.remove(hash);
    }
}

From source file:br.com.asisprojetos.DAO.TBRelatorioDiagnosticoDAO.java

public List<Map<String, Object>> getConsolidatedResults(
        List<String> listProtocols/*, List<String> listCodCliente*/ ) {

    List<Map<String, Object>> listResults = null;

    String SQL = " SELECT " + " tf.cor as COR, " + " tf.COD_FORMULA as COD_FORMULA  " + " FROM "
            + " SPF_TBITEM_RESULT tr   " + " INNER JOIN " + " SPF_TBFORMULA tf  "
            + " on tr.COD_FORMULA=tf.COD_FORMULA  " + " INNER JOIN " + " SPF_TBCTRL_PROCESSO  tcp   "
            + "  on tr.NUM_PROT=tcp.NUM_PROT cross  " + " JOIN " + " SPF_TBFORMULA tf2   " + "  WHERE "
            + " tr.COD_FORMULA = tf2.COD_FORMULA  " + " and ( tcp.NUM_PROT in ( :numProtocol ) )  "
            + " and ( tf2.NIVEL_FORMULA not in  (  '4' , '5' )  ) " +
            //" and ( tcp.COD_CLIENTE in ( :codCliente  ) ) " +
            " GROUP BY  tf.COD_FORMULA  ORDER BY tf.cor DESC ";

    MapSqlParameterSource namedParameters = new MapSqlParameterSource();

    namedParameters.addValue("numProtocol", listProtocols);
    //namedParameters.addValue( "codCliente" , listCodCliente );

    try {/*from  www . j a  v  a 2s .c o  m*/
        listResults = getNamedParameterJdbcTemplate().queryForList(SQL, namedParameters);
    } catch (DataAccessException ex) {
        logger.error("Erro ao efetuar busca no banco de dados. Message {}", ex);
    }

    return listResults;

}

From source file:io.lavagna.common.QueryType.java

private static SqlParameterSource extractParameters(Method m, Object[] args) {

    Class<?>[] parameterTypes = m.getParameterTypes();
    Annotation[][] parameterAnnotations = m.getParameterAnnotations();
    if (parameterAnnotations == null || parameterAnnotations.length == 0) {
        return new EmptySqlParameterSource();
    }/*from   ww w  .j  ava  2 s  . c  o m*/

    MapSqlParameterSource ps = new MapSqlParameterSource();
    for (int i = 0; i < args.length; i++) {
        String name = parameterName(parameterAnnotations[i]);
        if (name != null) {
            ps.addValue(name, args[i], StatementCreatorUtils.javaTypeToSqlParameterType(parameterTypes[i]));
        }
    }

    return ps;
}

From source file:com.branded.holdings.qpc.repository.jdbc.JdbcPetRepositoryImpl.java

/**
 * Creates a {@link MapSqlParameterSource} based on data values from the supplied {@link Pet} instance.
 *///w  w w . j a  v  a 2  s  . c o  m
private MapSqlParameterSource createPetParameterSource(Pet pet) {
    return new MapSqlParameterSource().addValue("id", pet.getId()).addValue("name", pet.getName())
            .addValue("birth_date", pet.getBirthDate().toDate()).addValue("type_id", pet.getType().getId())
            .addValue("owner_id", pet.getOwner().getId());
}

From source file:com.perry.infrastructure.call.CallDaoServiceImpl.java

@Override
public Truck assignTruck(long callId, long truckId) {
    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue("truckId", truckId);
    params.addValue("callId", callId);
    String sql = "update calls set truck_id = :truckId where call_id = :callId";
    namedParameterJdbcTemplate.update(sql, params);
    Truck truck = truckDaoService.getByIds(Arrays.asList(truckId)).get(0);
    return truck;

}

From source file:org.springframework.cloud.stream.app.jdbc.sink.JdbcSinkConfiguration.java

@Bean
@ServiceActivator(autoStartup = "false", inputChannel = Sink.INPUT)
public JdbcMessageHandler jdbcMessageHandler(DataSource dataSource) {
    final MultiValueMap<String, Expression> columnExpressionVariations = new LinkedMultiValueMap<>();
    for (Map.Entry<String, String> entry : properties.getColumns().entrySet()) {
        String value = entry.getValue();
        columnExpressionVariations.add(entry.getKey(), spelExpressionParser.parseExpression(value));
        if (!value.startsWith("payload")) {
            columnExpressionVariations.add(entry.getKey(),
                    spelExpressionParser.parseExpression("payload." + value));
        }/* w ww.  ja v a2 s.  c  om*/
    }
    JdbcMessageHandler jdbcMessageHandler = new JdbcMessageHandler(dataSource,
            generateSql(properties.getTableName(), columnExpressionVariations.keySet()));
    jdbcMessageHandler.setSqlParameterSourceFactory(new SqlParameterSourceFactory() {
        @Override
        public SqlParameterSource createParameterSource(Object o) {
            if (!(o instanceof Message)) {
                throw new IllegalArgumentException("Unable to handle type " + o.getClass().getName());
            }
            Message<?> message = (Message<?>) o;
            MapSqlParameterSource parameterSource = new MapSqlParameterSource();
            for (String key : columnExpressionVariations.keySet()) {
                List<Expression> spels = columnExpressionVariations.get(key);
                Object value = NOT_SET;
                EvaluationException lastException = null;
                for (Expression spel : spels) {
                    try {
                        value = spel.getValue(evaluationContext, message);
                        break;
                    } catch (EvaluationException e) {
                        lastException = e;
                    }
                }
                if (value == NOT_SET) {
                    if (lastException != null) {
                        logger.info(
                                "Could not find value for column '" + key + "': " + lastException.getMessage());
                    }
                    parameterSource.addValue(key, null);
                } else {
                    if (value instanceof JsonPropertyAccessor.ToStringFriendlyJsonNode) {
                        // Need to do some reflection until we have a getter for the Node
                        DirectFieldAccessor dfa = new DirectFieldAccessor(value);
                        JsonNode node = (JsonNode) dfa.getPropertyValue("node");
                        Object valueToUse;
                        if (node == null || node.isNull()) {
                            valueToUse = null;
                        } else if (node.isNumber()) {
                            valueToUse = node.numberValue();
                        } else if (node.isBoolean()) {
                            valueToUse = node.booleanValue();
                        } else {
                            valueToUse = node.textValue();
                        }
                        parameterSource.addValue(key, valueToUse);
                    } else {
                        parameterSource.addValue(key, value);
                    }
                }
            }
            return parameterSource;
        }
    });
    return jdbcMessageHandler;
}

From source file:fr.acxio.tools.agia.alfresco.HibernateNodeReader.java

/**
 * Retrieves nodes' IDs/*from   ww w .j  a v a  2s.c  o  m*/
 * 
 * @return a collection of IDs
 */
private List<Long> retrieveKeys() {

    synchronized (lock) {
        MapSqlParameterSource aParams = new MapSqlParameterSource();
        aParams.addValue(JOBSTEP_PARAM, currentStep);
        return jdbcTemplate.query(sqlQuery, aParams, new ParameterizedRowMapper<Long>() {
            public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getLong(1);
            }
        });
    }

}

From source file:com.lixiaocong.social.MyJdbcUsersConnection.java

public Set<String> findUserIdsConnectedTo(String providerId, Set<String> providerUserIds) {
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("providerId", providerId);
    parameters.addValue("providerUserIds", providerUserIds);
    final Set<String> localUserIds = new HashSet<String>();
    return new NamedParameterJdbcTemplate(jdbcTemplate).query(
            "select userId from " + tablePrefix
                    + "UserConnection where providerId = :providerId and providerUserId in (:providerUserIds)",
            parameters, new ResultSetExtractor<Set<String>>() {
                public Set<String> extractData(ResultSet rs) throws SQLException, DataAccessException {
                    while (rs.next()) {
                        localUserIds.add(rs.getString("userId"));
                    }/*from w  ww.  j av a2s.com*/
                    return localUserIds;
                }
            });
}

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

@Override
public Layer findById(Long id) {
    String sqlStatement = null;/*from w  w w.  j  a va 2  s .  c om*/
    MapSqlParameterSource args = null;
    Layer layer = null;

    sqlStatement = "SELECT * FROM " + this.table + " " + " WHERE id = :layer_id";

    args = new MapSqlParameterSource();
    args.addValue("layer_id", id);

    layer = getSimpleJdbcTemplate().queryForObject(sqlStatement, new LayerRowMapper(), args);

    return layer;
}

From source file:com.joliciel.jochre.boundaries.BoundaryDaoJdbc.java

@Override
public void saveSplit(Split split) {
    NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(this.getDataSource());
    MapSqlParameterSource paramSource = new MapSqlParameterSource();
    SplitInternal iSplit = (SplitInternal) split;

    paramSource.addValue("split_shape_id", split.getShapeId());
    paramSource.addValue("split_position", split.getPosition());
    String sql = null;//from w  w w .j  a  v  a2  s  .  co m

    if (split.isNew()) {
        sql = "SELECT nextval('ocr_split_id_seq')";
        LOG.debug(sql);
        int splitId = jt.queryForInt(sql, paramSource);
        paramSource.addValue("split_id", splitId);

        sql = "INSERT INTO ocr_split (split_id, split_shape_id, split_position) "
                + "VALUES (:split_id, :split_shape_id, :split_position)";

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

        iSplit.setId(splitId);
    } else {
        paramSource.addValue("split_id", split.getId());

        sql = "UPDATE ocr_split" + " SET split_shape_id = :split_shape_id"
                + ", split_position = :split_position" + " WHERE split_id = :split_id";

        LOG.debug(sql);
        logParameters(paramSource);
        jt.update(sql, paramSource);
    }
}