Search in sources :

Example 1 with SqlParameterValue

use of org.springframework.jdbc.core.SqlParameterValue in project spring-framework by spring-projects.

the class NamedParameterUtils method buildValueArray.

/**
	 * 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, 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;
}
Also used : SqlParameter(org.springframework.jdbc.core.SqlParameter) SqlParameterValue(org.springframework.jdbc.core.SqlParameterValue) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException)

Example 2 with SqlParameterValue

use of org.springframework.jdbc.core.SqlParameterValue in project spring-framework by spring-projects.

the class NamedParameterJdbcTemplateTests method testExecuteWithTypedParameters.

@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();
}
Also used : SqlParameterValue(org.springframework.jdbc.core.SqlParameterValue) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Test(org.junit.Test)

Example 3 with SqlParameterValue

use of org.springframework.jdbc.core.SqlParameterValue in project spring-framework by spring-projects.

the class NamedParameterJdbcTemplateTests method testQueryForObjectWithRowMapper.

@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, new RowMapper<Customer>() {

        @Override
        public Customer mapRow(ResultSet rs, int rownum) throws SQLException {
            Customer cust = new Customer();
            cust.setId(rs.getInt(COLUMN_NAMES[0]));
            cust.setForename(rs.getString(COLUMN_NAMES[1]));
            return cust;
        }
    });
    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();
}
Also used : SqlParameterValue(org.springframework.jdbc.core.SqlParameterValue) Customer(org.springframework.jdbc.Customer) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) Test(org.junit.Test)

Example 4 with SqlParameterValue

use of org.springframework.jdbc.core.SqlParameterValue in project spring-framework by spring-projects.

the class NamedParameterJdbcTemplateTests method testQueryWithRowMapper.

@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, new RowMapper<Customer>() {

        @Override
        public Customer mapRow(ResultSet rs, int rownum) throws SQLException {
            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();
}
Also used : SqlParameterValue(org.springframework.jdbc.core.SqlParameterValue) Customer(org.springframework.jdbc.Customer) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) Test(org.junit.Test)

Example 5 with SqlParameterValue

use of org.springframework.jdbc.core.SqlParameterValue in project spring-framework by spring-projects.

the class TableMetaDataContextTests method testMatchInParametersAndSqlTypeInfoWrapping.

@Test
public void testMatchInParametersAndSqlTypeInfoWrapping() throws Exception {
    final String TABLE = "customers";
    final String USER = "me";
    ResultSet metaDataResultSet = mock(ResultSet.class);
    given(metaDataResultSet.next()).willReturn(true, false);
    given(metaDataResultSet.getString("TABLE_SCHEM")).willReturn(USER);
    given(metaDataResultSet.getString("TABLE_NAME")).willReturn(TABLE);
    given(metaDataResultSet.getString("TABLE_TYPE")).willReturn("TABLE");
    ResultSet columnsResultSet = mock(ResultSet.class);
    given(columnsResultSet.next()).willReturn(true, true, true, true, false);
    given(columnsResultSet.getString("COLUMN_NAME")).willReturn("id", "name", "customersince", "version");
    given(columnsResultSet.getInt("DATA_TYPE")).willReturn(Types.INTEGER, Types.VARCHAR, Types.DATE, Types.NUMERIC);
    given(columnsResultSet.getBoolean("NULLABLE")).willReturn(false, true, true, false);
    given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
    given(databaseMetaData.getDatabaseProductName()).willReturn("1.0");
    given(databaseMetaData.getUserName()).willReturn(USER);
    given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
    given(databaseMetaData.getTables(null, null, TABLE, null)).willReturn(metaDataResultSet);
    given(databaseMetaData.getColumns(null, USER, TABLE, null)).willReturn(columnsResultSet);
    MapSqlParameterSource map = new MapSqlParameterSource();
    map.addValue("id", 1);
    map.addValue("name", "Sven");
    map.addValue("customersince", new Date());
    map.addValue("version", 0);
    map.registerSqlType("customersince", Types.DATE);
    map.registerSqlType("version", Types.NUMERIC);
    context.setTableName(TABLE);
    context.processMetaData(dataSource, new ArrayList<>(), new String[] {});
    List<Object> values = context.matchInParameterValuesWithInsertColumns(map);
    assertEquals("wrong number of parameters: ", 4, values.size());
    assertTrue("id not wrapped with type info", values.get(0) instanceof Number);
    assertTrue("name not wrapped with type info", values.get(1) instanceof String);
    assertTrue("date wrapped with type info", values.get(2) instanceof SqlParameterValue);
    assertTrue("version wrapped with type info", values.get(3) instanceof SqlParameterValue);
    verify(metaDataResultSet, atLeastOnce()).next();
    verify(columnsResultSet, atLeastOnce()).next();
    verify(metaDataResultSet).close();
    verify(columnsResultSet).close();
}
Also used : MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) SqlParameterValue(org.springframework.jdbc.core.SqlParameterValue) ResultSet(java.sql.ResultSet) Date(java.util.Date) Test(org.junit.Test)

Aggregations

SqlParameterValue (org.springframework.jdbc.core.SqlParameterValue)11 Test (org.junit.Test)8 ResultSet (java.sql.ResultSet)5 SQLException (java.sql.SQLException)5 Customer (org.springframework.jdbc.Customer)4 LinkedHashMap (java.util.LinkedHashMap)2 SqlParameter (org.springframework.jdbc.core.SqlParameter)2 PreparedStatement (java.sql.PreparedStatement)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1 DataAccessException (org.springframework.dao.DataAccessException)1 InvalidDataAccessApiUsageException (org.springframework.dao.InvalidDataAccessApiUsageException)1 RowCallbackHandler (org.springframework.jdbc.core.RowCallbackHandler)1 MapSqlParameterSource (org.springframework.jdbc.core.namedparam.MapSqlParameterSource)1