Java Code Examples for org.springframework.jdbc.core.SqlParameterValue

The following examples show how to use org.springframework.jdbc.core.SqlParameterValue. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: spring-analysis-note   Source File: SqlParameterSourceUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Create a wrapped value if parameter has type information, plain object if not.
 * @param source the source of parameter values and type information
 * @param parameterName the name of the parameter
 * @return the value object
 */
@Nullable
public static Object getTypedValue(SqlParameterSource source, String parameterName) {
	int sqlType = source.getSqlType(parameterName);
	if (sqlType != SqlParameterSource.TYPE_UNKNOWN) {
		if (source.getTypeName(parameterName) != null) {
			return new SqlParameterValue(sqlType, source.getTypeName(parameterName), source.getValue(parameterName));
		}
		else {
			return new SqlParameterValue(sqlType, source.getValue(parameterName));
		}
	}
	else {
		return source.getValue(parameterName);
	}
}
 
Example 2
@Test
public void testExecuteWithTypedParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
	Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
			(PreparedStatementCallback<Object>) ps -> {
				assertEquals(preparedStatement, ps);
				ps.executeUpdate();
				return "result";
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setObject(2, 1, Types.INTEGER);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 3
@Test
public void testQueryWithResultSetExtractor() throws SQLException {
	given(resultSet.next()).willReturn(true);
	given(resultSet.getInt("id")).willReturn(1);
	given(resultSet.getString("forename")).willReturn("rod");

	params.put("id", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("country", "UK");
	Customer cust = namedParameterTemplate.query(SELECT_NAMED_PARAMETERS, params,
			rs -> {
				rs.next();
				Customer cust1 = new Customer();
				cust1.setId(rs.getInt(COLUMN_NAMES[0]));
				cust1.setForename(rs.getString(COLUMN_NAMES[1]));
				return cust1;
			});

	assertTrue("Customer id was assigned correctly", cust.getId() == 1);
	assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
	verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setString(2, "UK");
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 4
@Test
public void testQueryWithRowCallbackHandler() throws SQLException {
	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getInt("id")).willReturn(1);
	given(resultSet.getString("forename")).willReturn("rod");

	params.put("id", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("country", "UK");
	final List<Customer> customers = new LinkedList<>();
	namedParameterTemplate.query(SELECT_NAMED_PARAMETERS, params, rs -> {
		Customer cust = new Customer();
		cust.setId(rs.getInt(COLUMN_NAMES[0]));
		cust.setForename(rs.getString(COLUMN_NAMES[1]));
		customers.add(cust);
	});

	assertEquals(1, customers.size());
	assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1);
	assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod"));
	verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setString(2, "UK");
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 5
@Test
public void testQueryWithRowMapper() throws SQLException {
	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getInt("id")).willReturn(1);
	given(resultSet.getString("forename")).willReturn("rod");

	params.put("id", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("country", "UK");
	List<Customer> customers = namedParameterTemplate.query(SELECT_NAMED_PARAMETERS, params,
			(rs, rownum) -> {
				Customer cust = new Customer();
				cust.setId(rs.getInt(COLUMN_NAMES[0]));
				cust.setForename(rs.getString(COLUMN_NAMES[1]));
				return cust;
			});
	assertEquals(1, customers.size());
	assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1);
	assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod"));
	verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setString(2, "UK");
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 6
@Test
public void testQueryForObjectWithRowMapper() throws SQLException {
	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getInt("id")).willReturn(1);
	given(resultSet.getString("forename")).willReturn("rod");

	params.put("id", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("country", "UK");
	Customer cust = namedParameterTemplate.queryForObject(SELECT_NAMED_PARAMETERS, params,
			(rs, rownum) -> {
				Customer cust1 = new Customer();
				cust1.setId(rs.getInt(COLUMN_NAMES[0]));
				cust1.setForename(rs.getString(COLUMN_NAMES[1]));
				return cust1;
			});
	assertTrue("Customer id was assigned correctly", cust.getId() == 1);
	assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
	verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setString(2, "UK");
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 7
Source Project: java-technology-stack   Source File: SqlParameterSourceUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Create a wrapped value if parameter has type information, plain object if not.
 * @param source the source of parameter values and type information
 * @param parameterName the name of the parameter
 * @return the value object
 */
@Nullable
public static Object getTypedValue(SqlParameterSource source, String parameterName) {
	int sqlType = source.getSqlType(parameterName);
	if (sqlType != SqlParameterSource.TYPE_UNKNOWN) {
		if (source.getTypeName(parameterName) != null) {
			return new SqlParameterValue(sqlType, source.getTypeName(parameterName), source.getValue(parameterName));
		}
		else {
			return new SqlParameterValue(sqlType, source.getValue(parameterName));
		}
	}
	else {
		return source.getValue(parameterName);
	}
}
 
Example 8
@Test
public void testExecuteWithTypedParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
	Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
			(PreparedStatementCallback<Object>) ps -> {
				assertEquals(preparedStatement, ps);
				ps.executeUpdate();
				return "result";
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setObject(2, 1, Types.INTEGER);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 9
@Test
public void testQueryWithResultSetExtractor() throws SQLException {
	given(resultSet.next()).willReturn(true);
	given(resultSet.getInt("id")).willReturn(1);
	given(resultSet.getString("forename")).willReturn("rod");

	params.put("id", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("country", "UK");
	Customer cust = namedParameterTemplate.query(SELECT_NAMED_PARAMETERS, params,
			rs -> {
				rs.next();
				Customer cust1 = new Customer();
				cust1.setId(rs.getInt(COLUMN_NAMES[0]));
				cust1.setForename(rs.getString(COLUMN_NAMES[1]));
				return cust1;
			});

	assertTrue("Customer id was assigned correctly", cust.getId() == 1);
	assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
	verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setString(2, "UK");
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 10
@Test
public void testQueryWithRowCallbackHandler() throws SQLException {
	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getInt("id")).willReturn(1);
	given(resultSet.getString("forename")).willReturn("rod");

	params.put("id", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("country", "UK");
	final List<Customer> customers = new LinkedList<>();
	namedParameterTemplate.query(SELECT_NAMED_PARAMETERS, params, rs -> {
		Customer cust = new Customer();
		cust.setId(rs.getInt(COLUMN_NAMES[0]));
		cust.setForename(rs.getString(COLUMN_NAMES[1]));
		customers.add(cust);
	});

	assertEquals(1, customers.size());
	assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1);
	assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod"));
	verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setString(2, "UK");
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 11
@Test
public void testQueryWithRowMapper() throws SQLException {
	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getInt("id")).willReturn(1);
	given(resultSet.getString("forename")).willReturn("rod");

	params.put("id", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("country", "UK");
	List<Customer> customers = namedParameterTemplate.query(SELECT_NAMED_PARAMETERS, params,
			(rs, rownum) -> {
				Customer cust = new Customer();
				cust.setId(rs.getInt(COLUMN_NAMES[0]));
				cust.setForename(rs.getString(COLUMN_NAMES[1]));
				return cust;
			});
	assertEquals(1, customers.size());
	assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1);
	assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod"));
	verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setString(2, "UK");
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 12
@Test
public void testQueryForObjectWithRowMapper() throws SQLException {
	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getInt("id")).willReturn(1);
	given(resultSet.getString("forename")).willReturn("rod");

	params.put("id", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("country", "UK");
	Customer cust = namedParameterTemplate.queryForObject(SELECT_NAMED_PARAMETERS, params,
			(rs, rownum) -> {
				Customer cust1 = new Customer();
				cust1.setId(rs.getInt(COLUMN_NAMES[0]));
				cust1.setForename(rs.getString(COLUMN_NAMES[1]));
				return cust1;
			});
	assertTrue("Customer id was assigned correctly", cust.getId() == 1);
	assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
	verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setString(2, "UK");
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 13
Source Project: metacat   Source File: MysqlUserMetadataService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * delete Data Metadatas.
 *
 * @param uris               uri list
 * @param removeDataMetadata flag to remove data meta data
 */
@SuppressWarnings("checkstyle:methodname")
private void _deleteDataMetadata(
    @Nullable final List<String> uris,
    final boolean removeDataMetadata
) {
    if (uris != null && !uris.isEmpty()) {
        final List<String> paramVariables = uris.stream().map(s -> "?").collect(Collectors.toList());
        final String[] aUris = uris.toArray(new String[0]);
        final String paramString = Joiner.on(",").skipNulls().join(paramVariables);
        final List<Long> ids = jdbcTemplate
            .query(String.format(SQL.GET_DATA_METADATA_IDS, paramString), aUris, (rs, rowNum) -> rs.getLong("id"));
        if (!ids.isEmpty()) {
            final List<String> idParamVariables = ids.stream().map(s -> "?").collect(Collectors.toList());
            final SqlParameterValue[] aIds = ids.stream().map(id -> new SqlParameterValue(Types.BIGINT, id))
                .toArray(SqlParameterValue[]::new);
            final String idParamString = Joiner.on(",").skipNulls().join(idParamVariables);
            jdbcTemplate.update(String.format(SQL.DELETE_DATA_METADATA_DELETE, idParamString), (Object[]) aIds);
            if (removeDataMetadata) {
                jdbcTemplate.update(String.format(SQL.DELETE_DATA_METADATA, idParamString), (Object[]) aIds);
            }
        }
    }
}
 
Example 14
Source Project: metacat   Source File: MySqlTagService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void delete(final QualifiedName name, final boolean updateUserMetadata) {
    try {
        jdbcTemplate
            .update(SQL_DELETE_TAG_ITEM_TAGS_BY_NAME, new SqlParameterValue(Types.VARCHAR, name.toString()));
        jdbcTemplate.update(SQL_DELETE_TAG_ITEM, new SqlParameterValue(Types.VARCHAR, name.toString()));
        if (updateUserMetadata) {
            // Set the tags in user metadata
            final Map<String, Set<String>> data = Maps.newHashMap();
            data.put(NAME_TAGS, Sets.newHashSet());
            userMetadataService
                .saveDefinitionMetadata(name, "admin", Optional.of(metacatJson.toJsonObject(data)),
                    true);
        }
    } catch (Exception e) {
        final String message = String.format("Failed to delete all tags for name %s", name);
        log.error(message, e);
        throw new UserMetadataServiceException(message, e);
    }
}
 
Example 15
Source Project: metacat   Source File: MySqlTagService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * remove.
 *
 * @param name               qualifiedName
 * @param tags               tags
 * @param updateUserMetadata flag to update user metadata
 */
public void remove(final QualifiedName name, final Set<String> tags, final boolean updateUserMetadata) {
    try {
        jdbcTemplate.update(String.format(SQL_DELETE_TAG_ITEM_TAGS_BY_NAME_TAGS,
            "'" + Joiner.on("','").skipNulls().join(tags) + "'"),
            new SqlParameterValue(Types.VARCHAR, name.toString()));
        if (updateUserMetadata) {
            final TagItem tagItem = get(name);
            tagItem.getValues().removeAll(tags);
            final Map<String, Set<String>> data = Maps.newHashMap();
            data.put(NAME_TAGS, tagItem.getValues());
            userMetadataService
                .saveDefinitionMetadata(name, "admin", Optional.of(metacatJson.toJsonObject(data)),
                    true);
        }
    } catch (Exception e) {
        final String message = String.format("Failed to remove tags for name %s", name);
        log.error(message, e);
        throw new UserMetadataServiceException(message, e);
    }
}
 
Example 16
Source Project: metacat   Source File: DirectSqlSavePartition.java    License: Apache License 2.0 6 votes vote down vote up
private List<PartitionSequenceIds> getPartitionSequenceIds(final QualifiedName tableName,
                                                           final List<String> partitionNames) {
    final List<String> paramVariables = partitionNames.stream().map(s -> "?").collect(Collectors.toList());
    final String paramVariableString = Joiner.on(",").skipNulls().join(paramVariables);
    final SqlParameterValue[] values = new SqlParameterValue[partitionNames.size() + 2];
    int index = 0;
    values[index++] = new SqlParameterValue(Types.VARCHAR, tableName.getDatabaseName());
    values[index++] = new SqlParameterValue(Types.VARCHAR, tableName.getTableName());
    for (String partitionName : partitionNames) {
        values[index++] = new SqlParameterValue(Types.VARCHAR, partitionName);
    }
    return jdbcTemplate.query(
        String.format(SQL.PARTITIONS_SELECT, paramVariableString), values,
        (rs, rowNum) -> new PartitionSequenceIds(rs.getLong("part_id"), rs.getLong("sd_id"),
            rs.getLong("serde_id")));
}
 
Example 17
@Test
public void testExecuteWithTypedParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
	Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
			new PreparedStatementCallback<Object>() {
				@Override
				public Object doInPreparedStatement(PreparedStatement ps)
						throws SQLException {
					assertEquals(preparedStatement, ps);
					ps.executeUpdate();
					return "result";
				}
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setObject(2, 1, Types.INTEGER);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 18
@Test
public void testExecuteWithTypedParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
	Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
			new PreparedStatementCallback<Object>() {
				@Override
				public Object doInPreparedStatement(PreparedStatement ps)
						throws SQLException {
					assertEquals(preparedStatement, ps);
					ps.executeUpdate();
					return "result";
				}
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setObject(2, 1, Types.INTEGER);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 19
Source Project: spring-analysis-note   Source File: AbstractSqlParameterSource.java    License: MIT License 5 votes vote down vote up
/**
 * Enumerate the parameter names and values with their corresponding SQL type if available,
 * or just return the simple {@code SqlParameterSource} implementation class name otherwise.
 * @since 5.2
 * @see #getParameterNames()
 */
@Override
public String toString() {
	String[] parameterNames = getParameterNames();
	if (parameterNames != null) {
		StringJoiner result = new StringJoiner(", ", getClass().getSimpleName() + " {", "}");
		for (String parameterName : parameterNames) {
			Object value = getValue(parameterName);
			if (value instanceof SqlParameterValue) {
				value = ((SqlParameterValue) value).getValue();
			}
			String typeName = getTypeName(parameterName);
			if (typeName == null) {
				int sqlType = getSqlType(parameterName);
				if (sqlType != TYPE_UNKNOWN) {
					typeName = JdbcUtils.resolveTypeName(sqlType);
					if (typeName == null) {
						typeName = String.valueOf(sqlType);
					}
				}
			}
			StringBuilder entry = new StringBuilder();
			entry.append(parameterName).append('=').append(value);
			if (typeName != null) {
				entry.append(" (type:").append(typeName).append(')');
			}
			result.add(entry);
		}
		return result.toString();
	}
	else {
		return getClass().getSimpleName();
	}
}
 
Example 20
Source Project: spring-analysis-note   Source File: NamedParameterUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Convert a Map of named parameter values to a corresponding array.
 * @param parsedSql the parsed SQL statement
 * @param paramSource the source for named parameters
 * @param declaredParams the List of declared SqlParameter objects
 * (may be {@code null}). If specified, the parameter metadata will
 * be built into the value array in the form of SqlParameterValue objects.
 * @return the array of values
 */
public static Object[] buildValueArray(
		ParsedSql parsedSql, SqlParameterSource paramSource, @Nullable List<SqlParameter> declaredParams) {

	Object[] paramArray = new Object[parsedSql.getTotalParameterCount()];
	if (parsedSql.getNamedParameterCount() > 0 && parsedSql.getUnnamedParameterCount() > 0) {
		throw new InvalidDataAccessApiUsageException(
				"Not allowed to mix named and traditional ? placeholders. You have " +
				parsedSql.getNamedParameterCount() + " named parameter(s) and " +
				parsedSql.getUnnamedParameterCount() + " traditional placeholder(s) in statement: " +
				parsedSql.getOriginalSql());
	}
	List<String> paramNames = parsedSql.getParameterNames();
	for (int i = 0; i < paramNames.size(); i++) {
		String paramName = paramNames.get(i);
		try {
			Object value = paramSource.getValue(paramName);
			SqlParameter param = findParameter(declaredParams, paramName, i);
			paramArray[i] = (param != null ? new SqlParameterValue(param, value) : value);
		}
		catch (IllegalArgumentException ex) {
			throw new InvalidDataAccessApiUsageException(
					"No value supplied for the SQL parameter '" + paramName + "': " + ex.getMessage());
		}
	}
	return paramArray;
}
 
Example 21
Source Project: spring-analysis-note   Source File: MapSqlParameterSource.java    License: MIT License 5 votes vote down vote up
/**
 * Add a parameter to this parameter source.
 * @param paramName the name of the parameter
 * @param value the value of the parameter
 * @return a reference to this parameter source,
 * so it's possible to chain several calls together
 */
public MapSqlParameterSource addValue(String paramName, @Nullable Object value) {
	Assert.notNull(paramName, "Parameter name must not be null");
	this.values.put(paramName, value);
	if (value instanceof SqlParameterValue) {
		registerSqlType(paramName, ((SqlParameterValue) value).getSqlType());
	}
	return this;
}
 
Example 22
Source Project: spring-analysis-note   Source File: MapSqlParameterSource.java    License: MIT License 5 votes vote down vote up
/**
 * Add a Map of parameters to this parameter source.
 * @param values a Map holding existing parameter values (can be {@code null})
 * @return a reference to this parameter source,
 * so it's possible to chain several calls together
 */
public MapSqlParameterSource addValues(@Nullable Map<String, ?> values) {
	if (values != null) {
		values.forEach((key, value) -> {
			this.values.put(key, value);
			if (value instanceof SqlParameterValue) {
				registerSqlType(key, ((SqlParameterValue) value).getSqlType());
			}
		});
	}
	return this;
}
 
Example 23
Source Project: spring-analysis-note   Source File: MapSqlParameterSourceTests.java    License: MIT License 5 votes vote down vote up
@Test
public void sqlParameterValueRegistersSqlType() {
	MapSqlParameterSource msps = new MapSqlParameterSource("FOO", new SqlParameterValue(Types.NUMERIC, "Foo"));
	assertEquals("Correct SQL Type not registered", 2, msps.getSqlType("FOO"));
	MapSqlParameterSource msps2 = new MapSqlParameterSource();
	msps2.addValues(msps.getValues());
	assertEquals("Correct SQL Type not registered", 2, msps2.getSqlType("FOO"));
}
 
Example 24
@Test
public void testUpdateWithTypedParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
	int rowsAffected = namedParameterTemplate.update(UPDATE_NAMED_PARAMETERS, params);

	assertEquals(1, rowsAffected);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setObject(2, 1, Types.INTEGER);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 25
Source Project: java-technology-stack   Source File: NamedParameterUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Convert a Map of named parameter values to a corresponding array.
 * @param parsedSql the parsed SQL statement
 * @param paramSource the source for named parameters
 * @param declaredParams the List of declared SqlParameter objects
 * (may be {@code null}). If specified, the parameter metadata will
 * be built into the value array in the form of SqlParameterValue objects.
 * @return the array of values
 */
public static Object[] buildValueArray(
		ParsedSql parsedSql, SqlParameterSource paramSource, @Nullable List<SqlParameter> declaredParams) {

	Object[] paramArray = new Object[parsedSql.getTotalParameterCount()];
	if (parsedSql.getNamedParameterCount() > 0 && parsedSql.getUnnamedParameterCount() > 0) {
		throw new InvalidDataAccessApiUsageException(
				"Not allowed to mix named and traditional ? placeholders. You have " +
				parsedSql.getNamedParameterCount() + " named parameter(s) and " +
				parsedSql.getUnnamedParameterCount() + " traditional placeholder(s) in statement: " +
				parsedSql.getOriginalSql());
	}
	List<String> paramNames = parsedSql.getParameterNames();
	for (int i = 0; i < paramNames.size(); i++) {
		String paramName = paramNames.get(i);
		try {
			Object value = paramSource.getValue(paramName);
			SqlParameter param = findParameter(declaredParams, paramName, i);
			paramArray[i] = (param != null ? new SqlParameterValue(param, value) : value);
		}
		catch (IllegalArgumentException ex) {
			throw new InvalidDataAccessApiUsageException(
					"No value supplied for the SQL parameter '" + paramName + "': " + ex.getMessage());
		}
	}
	return paramArray;
}
 
Example 26
Source Project: java-technology-stack   Source File: MapSqlParameterSource.java    License: MIT License 5 votes vote down vote up
/**
 * Add a parameter to this parameter source.
 * @param paramName the name of the parameter
 * @param value the value of the parameter
 * @return a reference to this parameter source,
 * so it's possible to chain several calls together
 */
public MapSqlParameterSource addValue(String paramName, @Nullable Object value) {
	Assert.notNull(paramName, "Parameter name must not be null");
	this.values.put(paramName, value);
	if (value instanceof SqlParameterValue) {
		registerSqlType(paramName, ((SqlParameterValue) value).getSqlType());
	}
	return this;
}
 
Example 27
Source Project: java-technology-stack   Source File: MapSqlParameterSource.java    License: MIT License 5 votes vote down vote up
/**
 * Add a Map of parameters to this parameter source.
 * @param values a Map holding existing parameter values (can be {@code null})
 * @return a reference to this parameter source,
 * so it's possible to chain several calls together
 */
public MapSqlParameterSource addValues(@Nullable Map<String, ?> values) {
	if (values != null) {
		values.forEach((key, value) -> {
			this.values.put(key, value);
			if (value instanceof SqlParameterValue) {
				registerSqlType(key, ((SqlParameterValue) value).getSqlType());
			}
		});
	}
	return this;
}
 
Example 28
Source Project: java-technology-stack   Source File: MapSqlParameterSourceTests.java    License: MIT License 5 votes vote down vote up
@Test
public void sqlParameterValueRegistersSqlType() throws Exception {
	MapSqlParameterSource msps = new MapSqlParameterSource("FOO", new SqlParameterValue(2, "Foo"));
	assertEquals("Correct SQL Type not registered", 2, msps.getSqlType("FOO"));
	MapSqlParameterSource msps2 = new MapSqlParameterSource();
	msps2.addValues(msps.getValues());
	assertEquals("Correct SQL Type not registered", 2, msps2.getSqlType("FOO"));
}
 
Example 29
@Test
public void testUpdateWithTypedParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
	int rowsAffected = namedParameterTemplate.update(UPDATE_NAMED_PARAMETERS, params);

	assertEquals(1, rowsAffected);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setObject(2, 1, Types.INTEGER);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 30
Source Project: opscenter   Source File: ProcedureParameterUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert a Map of named parameter values to a corresponding array.
 * @param parsedSqlBean the parsed SQL statement
 * @param paramSource the source for named parameters
 * @param declaredParams the List of declared SqlParameter objects
 * (may be {@code null}). If specified, the parameter metadata will
 * be built into the value array in the form of SqlParameterValue objects.
 * @return the array of values
 */
public static Object[] buildValueArray(
		ParsedSqlBean parsedSqlBean, SqlParameterSource paramSource, @Nullable List<SqlParameter> declaredParams) {

	Object[] paramArray = new Object[parsedSqlBean.getTotalParameterCount()];
	if (parsedSqlBean.getNamedParameterCount() > 0 && parsedSqlBean.getUnnamedParameterCount() > 0) {
		throw new InvalidDataAccessApiUsageException(
				"Not allowed to mix named and traditional ? placeholders. You have " +
				parsedSqlBean.getNamedParameterCount() + " named parameter(s) and " +
				parsedSqlBean.getUnnamedParameterCount() + " traditional placeholder(s) in statement: " +
				parsedSqlBean.getOriginalSql());
	}
	List<String> paramNames = parsedSqlBean.getParameterNames();
	for (int i = 0; i < paramNames.size(); i++) {
		String paramName = paramNames.get(i);
		try {
			Object value = paramSource.getValue(paramName);
			SqlParameter param = findParameter(declaredParams, paramName, i);
			paramArray[i] = (param != null ? new SqlParameterValue(param, value) : value);
		}
		catch (IllegalArgumentException ex) {
			throw new InvalidDataAccessApiUsageException(
					"No value supplied for the SQL parameter '" + paramName + "': " + ex.getMessage());
		}
	}
	return paramArray;
}