org.springframework.jdbc.core.SqlParameter Java Examples
The following examples show how to use
org.springframework.jdbc.core.SqlParameter.
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 File: NamedParameterJdbcTemplate.java From effectivejava with Apache License 2.0 | 6 votes |
@Override public int update( String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, String[] keyColumnNames) throws DataAccessException { ParsedSql parsedSql = getParsedSql(sql); String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource); Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, null); List<SqlParameter> declaredParameters = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource); PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlToUse, declaredParameters); if (keyColumnNames != null) { pscf.setGeneratedKeysColumnNames(keyColumnNames); } else { pscf.setReturnGeneratedKeys(true); } return getJdbcOperations().update(pscf.newPreparedStatementCreator(params), generatedKeyHolder); }
Example #2
Source File: SqlQueryTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void testQueryWithMissingMapParams() { MappingSqlQuery<Integer> query = new MappingSqlQuery<Integer>() { @Override protected Integer mapRow(ResultSet rs, int rownum) throws SQLException { return rs.getInt(1); } }; query.setDataSource(dataSource); query.setSql(SELECT_ID_WHERE); query.declareParameter(new SqlParameter(COLUMN_NAMES[0], COLUMN_TYPES[0])); query.declareParameter(new SqlParameter(COLUMN_NAMES[1], COLUMN_TYPES[1])); query.compile(); assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() -> query.executeByNamedParam(Collections.singletonMap(COLUMN_NAMES[0], "value"))); }
Example #3
Source File: RdbmsOperation.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * Validate the named parameters passed to an execute method based on declared parameters. * Subclasses should invoke this method before every {@code executeQuery()} or * {@code update()} method. * @param parameters parameter Map supplied. May be {@code null}. * @throws InvalidDataAccessApiUsageException if the parameters are invalid */ protected void validateNamedParameters(Map<String, ?> parameters) throws InvalidDataAccessApiUsageException { checkCompiled(); Map<String, ?> paramsToUse = (parameters != null ? parameters : Collections.<String, Object> emptyMap()); int declaredInParameters = 0; for (SqlParameter param : this.declaredParameters) { if (param.isInputValueProvided()) { if (!supportsLobParameters() && (param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) { throw new InvalidDataAccessApiUsageException( "BLOB or CLOB parameters are not allowed for this kind of operation"); } if (param.getName() != null && !paramsToUse.containsKey(param.getName())) { throw new InvalidDataAccessApiUsageException("The parameter named '" + param.getName() + "' was not among the parameters supplied: " + paramsToUse.keySet()); } declaredInParameters++; } } validateParameterCount(paramsToUse.size(), declaredInParameters); }
Example #4
Source File: RdbmsOperation.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Validate the parameters passed to an execute method based on declared parameters. * Subclasses should invoke this method before every {@code executeQuery()} * or {@code update()} method. * @param parameters parameters supplied (may be {@code null}) * @throws InvalidDataAccessApiUsageException if the parameters are invalid */ protected void validateParameters(Object[] parameters) throws InvalidDataAccessApiUsageException { checkCompiled(); int declaredInParameters = 0; for (SqlParameter param : this.declaredParameters) { if (param.isInputValueProvided()) { if (!supportsLobParameters() && (param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) { throw new InvalidDataAccessApiUsageException( "BLOB or CLOB parameters are not allowed for this kind of operation"); } declaredInParameters++; } } validateParameterCount((parameters != null ? parameters.length : 0), declaredInParameters); }
Example #5
Source File: RdbmsOperation.java From effectivejava with Apache License 2.0 | 6 votes |
/** * Validate the parameters passed to an execute method based on declared parameters. * Subclasses should invoke this method before every {@code executeQuery()} * or {@code update()} method. * @param parameters parameters supplied (may be {@code null}) * @throws InvalidDataAccessApiUsageException if the parameters are invalid */ protected void validateParameters(Object[] parameters) throws InvalidDataAccessApiUsageException { checkCompiled(); int declaredInParameters = 0; for (SqlParameter param : this.declaredParameters) { if (param.isInputValueProvided()) { if (!supportsLobParameters() && (param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) { throw new InvalidDataAccessApiUsageException( "BLOB or CLOB parameters are not allowed for this kind of operation"); } declaredInParameters++; } } validateParameterCount((parameters != null ? parameters.length : 0), declaredInParameters); }
Example #6
Source File: RdbmsOperation.java From spring-analysis-note with MIT License | 6 votes |
/** * Validate the named parameters passed to an execute method based on declared parameters. * Subclasses should invoke this method before every {@code executeQuery()} or * {@code update()} method. * @param parameters parameter Map supplied (may be {@code null}) * @throws InvalidDataAccessApiUsageException if the parameters are invalid */ protected void validateNamedParameters(@Nullable Map<String, ?> parameters) throws InvalidDataAccessApiUsageException { checkCompiled(); Map<String, ?> paramsToUse = (parameters != null ? parameters : Collections.<String, Object> emptyMap()); int declaredInParameters = 0; for (SqlParameter param : this.declaredParameters) { if (param.isInputValueProvided()) { if (!supportsLobParameters() && (param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) { throw new InvalidDataAccessApiUsageException( "BLOB or CLOB parameters are not allowed for this kind of operation"); } if (param.getName() != null && !paramsToUse.containsKey(param.getName())) { throw new InvalidDataAccessApiUsageException("The parameter named '" + param.getName() + "' was not among the parameters supplied: " + paramsToUse.keySet()); } declaredInParameters++; } } validateParameterCount(paramsToUse.size(), declaredInParameters); }
Example #7
Source File: RdbmsOperation.java From spring-analysis-note with MIT License | 6 votes |
/** * Validate the parameters passed to an execute method based on declared parameters. * Subclasses should invoke this method before every {@code executeQuery()} * or {@code update()} method. * @param parameters parameters supplied (may be {@code null}) * @throws InvalidDataAccessApiUsageException if the parameters are invalid */ protected void validateParameters(@Nullable Object[] parameters) throws InvalidDataAccessApiUsageException { checkCompiled(); int declaredInParameters = 0; for (SqlParameter param : this.declaredParameters) { if (param.isInputValueProvided()) { if (!supportsLobParameters() && (param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) { throw new InvalidDataAccessApiUsageException( "BLOB or CLOB parameters are not allowed for this kind of operation"); } declaredInParameters++; } } validateParameterCount((parameters != null ? parameters.length : 0), declaredInParameters); }
Example #8
Source File: AbstractJdbcCall.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * Delegate method to perform the actual compilation. * <p>Subclasses can override this template method to perform their own compilation. * Invoked after this base class's compilation is complete. */ protected void compileInternal() { this.callMetaDataContext.initializeMetaData(getJdbcTemplate().getDataSource()); // Iterate over the declared RowMappers and register the corresponding SqlParameter for (Map.Entry<String, RowMapper<?>> entry : this.declaredRowMappers.entrySet()) { SqlParameter resultSetParameter = this.callMetaDataContext.createReturnResultSetParameter(entry.getKey(), entry.getValue()); this.declaredParameters.add(resultSetParameter); } this.callMetaDataContext.processParameters(this.declaredParameters); this.callString = this.callMetaDataContext.createCallString(); if (logger.isDebugEnabled()) { logger.debug("Compiled stored procedure. Call string is [" + this.callString + "]"); } this.callableStatementFactory = new CallableStatementCreatorFactory(getCallString(), this.callMetaDataContext.getCallParameters()); this.callableStatementFactory.setNativeJdbcExtractor(getJdbcTemplate().getNativeJdbcExtractor()); onCompileInternal(); }
Example #9
Source File: RdbmsOperation.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Validate the named parameters passed to an execute method based on declared parameters. * Subclasses should invoke this method before every {@code executeQuery()} or * {@code update()} method. * @param parameters parameter Map supplied (may be {@code null}) * @throws InvalidDataAccessApiUsageException if the parameters are invalid */ protected void validateNamedParameters(Map<String, ?> parameters) throws InvalidDataAccessApiUsageException { checkCompiled(); Map<String, ?> paramsToUse = (parameters != null ? parameters : Collections.<String, Object> emptyMap()); int declaredInParameters = 0; for (SqlParameter param : this.declaredParameters) { if (param.isInputValueProvided()) { if (!supportsLobParameters() && (param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) { throw new InvalidDataAccessApiUsageException( "BLOB or CLOB parameters are not allowed for this kind of operation"); } if (param.getName() != null && !paramsToUse.containsKey(param.getName())) { throw new InvalidDataAccessApiUsageException("The parameter named '" + param.getName() + "' was not among the parameters supplied: " + paramsToUse.keySet()); } declaredInParameters++; } } validateParameterCount(paramsToUse.size(), declaredInParameters); }
Example #10
Source File: AbstractJdbcCall.java From effectivejava with Apache License 2.0 | 6 votes |
/** * Method to perform the actual compilation. Subclasses can override this template method to perform * their own compilation. Invoked after this base class's compilation is complete. */ protected void compileInternal() { this.callMetaDataContext.initializeMetaData(getJdbcTemplate().getDataSource()); // iterate over the declared RowMappers and register the corresponding SqlParameter for (Map.Entry<String, RowMapper<?>> entry : this.declaredRowMappers.entrySet()) { SqlParameter resultSetParameter = this.callMetaDataContext.createReturnResultSetParameter(entry.getKey(), entry.getValue()); this.declaredParameters.add(resultSetParameter); } this.callMetaDataContext.processParameters(this.declaredParameters); this.callString = this.callMetaDataContext.createCallString(); if (logger.isDebugEnabled()) { logger.debug("Compiled stored procedure. Call string is [" + this.callString + "]"); } this.callableStatementFactory = new CallableStatementCreatorFactory(getCallString(), this.callMetaDataContext.getCallParameters()); this.callableStatementFactory.setNativeJdbcExtractor(getJdbcTemplate().getNativeJdbcExtractor()); onCompileInternal(); }
Example #11
Source File: AbstractJdbcCall.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Delegate method to perform the actual compilation. * <p>Subclasses can override this template method to perform their own compilation. * Invoked after this base class's compilation is complete. */ protected void compileInternal() { this.callMetaDataContext.initializeMetaData(getJdbcTemplate().getDataSource()); // Iterate over the declared RowMappers and register the corresponding SqlParameter for (Map.Entry<String, RowMapper<?>> entry : this.declaredRowMappers.entrySet()) { SqlParameter resultSetParameter = this.callMetaDataContext.createReturnResultSetParameter(entry.getKey(), entry.getValue()); this.declaredParameters.add(resultSetParameter); } this.callMetaDataContext.processParameters(this.declaredParameters); this.callString = this.callMetaDataContext.createCallString(); if (logger.isDebugEnabled()) { logger.debug("Compiled stored procedure. Call string is [" + this.callString + "]"); } this.callableStatementFactory = new CallableStatementCreatorFactory(getCallString(), this.callMetaDataContext.getCallParameters()); this.callableStatementFactory.setNativeJdbcExtractor(getJdbcTemplate().getNativeJdbcExtractor()); onCompileInternal(); }
Example #12
Source File: SqlQueryTests.java From effectivejava with Apache License 2.0 | 6 votes |
@Test public void testQueryWithoutEnoughParams() { MappingSqlQuery<Integer> query = new MappingSqlQuery<Integer>() { @Override protected Integer mapRow(ResultSet rs, int rownum) throws SQLException { return rs.getInt(1); } }; query.setDataSource(dataSource); query.setSql(SELECT_ID_WHERE); query.declareParameter(new SqlParameter(COLUMN_NAMES[0], COLUMN_TYPES[0])); query.declareParameter(new SqlParameter(COLUMN_NAMES[1], COLUMN_TYPES[1])); query.compile(); thrown.expect(InvalidDataAccessApiUsageException.class); query.execute(); }
Example #13
Source File: RdbmsOperation.java From java-technology-stack with MIT License | 6 votes |
/** * Validate the parameters passed to an execute method based on declared parameters. * Subclasses should invoke this method before every {@code executeQuery()} * or {@code update()} method. * @param parameters parameters supplied (may be {@code null}) * @throws InvalidDataAccessApiUsageException if the parameters are invalid */ protected void validateParameters(@Nullable Object[] parameters) throws InvalidDataAccessApiUsageException { checkCompiled(); int declaredInParameters = 0; for (SqlParameter param : this.declaredParameters) { if (param.isInputValueProvided()) { if (!supportsLobParameters() && (param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) { throw new InvalidDataAccessApiUsageException( "BLOB or CLOB parameters are not allowed for this kind of operation"); } declaredInParameters++; } } validateParameterCount((parameters != null ? parameters.length : 0), declaredInParameters); }
Example #14
Source File: DatasourceServletAction.java From ureport with Apache License 2.0 | 5 votes |
protected PreparedStatementCreator getPreparedStatementCreator(String sql, SqlParameterSource paramSource) { ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource); Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, null); List<SqlParameter> declaredParameters = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource); PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlToUse, declaredParameters); return pscf.newPreparedStatementCreator(params); }
Example #15
Source File: SqlQueryTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void testUnnamedParameterDeclarationWithNamedParameterQuery() throws SQLException { class CustomerQuery extends MappingSqlQuery<Customer> { public CustomerQuery(DataSource ds) { super(ds, SELECT_ID_FORENAME_WHERE); setResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE); declareParameter(new SqlParameter(Types.NUMERIC)); compile(); } @Override protected 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; } public Customer findCustomer(int id) { Map<String, Integer> params = new HashMap<>(); params.put("id", id); return executeByNamedParam(params).get(0); } } // Query should not succeed since parameter declaration did not specify parameter name CustomerQuery query = new CustomerQuery(dataSource); assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() -> query.findCustomer(1)); }
Example #16
Source File: SqlUpdateTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
public GeneratedKeysUpdater() { setSql(INSERT_GENERATE_KEYS); setDataSource(dataSource); declareParameter(new SqlParameter(Types.VARCHAR)); setReturnGeneratedKeys(true); compile(); }
Example #17
Source File: NamedParameterUtils.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * 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; }
Example #18
Source File: SimpleJdbcCallTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void testAddInvoiceProcWithoutMetaDataUsingArrayParams() throws Exception { initializeAddInvoiceWithoutMetaData(false); SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withProcedureName("add_invoice"); adder.declareParameters( new SqlParameter("amount", Types.INTEGER), new SqlParameter("custid", Types.INTEGER), new SqlOutParameter("newid", Types.INTEGER)); Number newId = adder.executeObject(Number.class, 1103, 3); assertEquals(4, newId.intValue()); verifyAddInvoiceWithoutMetaData(false); verify(connection, atLeastOnce()).close(); }
Example #19
Source File: SimpleJdbcCallTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void testAddInvoiceFuncWithoutMetaDataUsingArrayParams() throws Exception { initializeAddInvoiceWithoutMetaData(true); SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withFunctionName("add_invoice"); adder.declareParameters( new SqlOutParameter("return", Types.INTEGER), new SqlParameter("amount", Types.INTEGER), new SqlParameter("custid", Types.INTEGER)); Number newId = adder.executeFunction(Number.class, 1103, 3); assertEquals(4, newId.intValue()); verifyAddInvoiceWithoutMetaData(true); verify(connection, atLeastOnce()).close(); }
Example #20
Source File: PostgresCallMetaDataProvider.java From effectivejava with Apache License 2.0 | 5 votes |
@Override public SqlParameter createDefaultOutParameter(String parameterName, CallParameterMetaData meta) { if (meta.getSqlType() == Types.OTHER && "refcursor".equals(meta.getTypeName())) { return new SqlOutParameter(parameterName, getRefCursorSqlType(), new ColumnMapRowMapper()); } else { return super.createDefaultOutParameter(parameterName, meta); } }
Example #21
Source File: SimpleJdbcConferenceDaoImpl.java From spring4-sandbox with Apache License 2.0 | 5 votes |
public ConferenceUpdate(DataSource ds, String sql, Conference conference) { super(ds, sql); this.conference = conference; declareParameter(new SqlParameter(Types.VARCHAR)); declareParameter(new SqlParameter(Types.VARCHAR)); declareParameter(new SqlParameter(Types.VARCHAR)); declareParameter(new SqlParameter(Types.TIMESTAMP)); declareParameter(new SqlParameter(Types.TIMESTAMP)); declareParameter(new SqlParameter(Types.NUMERIC)); compile(); }
Example #22
Source File: SqlUpdateTests.java From spring-analysis-note with MIT License | 5 votes |
public GeneratedKeysUpdater() { setSql(INSERT_GENERATE_KEYS); setDataSource(dataSource); declareParameter(new SqlParameter(Types.VARCHAR)); setReturnGeneratedKeys(true); compile(); }
Example #23
Source File: AbstractJdbcCall.java From spring-analysis-note with MIT License | 5 votes |
/** * Add a declared parameter to the list of parameters for the call. * <p>Only parameters declared as {@code SqlParameter} and {@code SqlInOutParameter} will * be used to provide input values. This is different from the {@code StoredProcedure} * class which - for backwards compatibility reasons - allows input values to be provided * for parameters declared as {@code SqlOutParameter}. * @param parameter the {@link SqlParameter} to add */ public void addDeclaredParameter(SqlParameter parameter) { Assert.notNull(parameter, "The supplied parameter must not be null"); if (!StringUtils.hasText(parameter.getName())) { throw new InvalidDataAccessApiUsageException( "You must specify a parameter name when declaring parameters for \"" + getProcedureName() + "\""); } this.declaredParameters.add(parameter); if (logger.isDebugEnabled()) { logger.debug("Added declared parameter for [" + getProcedureName() + "]: " + parameter.getName()); } }
Example #24
Source File: SqlCall.java From effectivejava with Apache License 2.0 | 5 votes |
/** * Overridden method to configure the CallableStatementCreatorFactory * based on our declared parameters. * @see RdbmsOperation#compileInternal() */ @Override protected final void compileInternal() { if (isSqlReadyForUse()) { this.callString = getSql(); } else { List<SqlParameter> parameters = getDeclaredParameters(); int parameterCount = 0; if (isFunction()) { this.callString = "{? = call " + getSql() + "("; parameterCount = -1; } else { this.callString = "{call " + getSql() + "("; } for (SqlParameter parameter : parameters) { if (!(parameter.isResultsParameter())) { if (parameterCount > 0) { this.callString += ", "; } if (parameterCount >= 0) { this.callString += "?"; } parameterCount++; } } this.callString += ")}"; } if (logger.isDebugEnabled()) { logger.debug("Compiled stored procedure. Call string is [" + getCallString() + "]"); } this.callableStatementFactory = new CallableStatementCreatorFactory(getCallString(), getDeclaredParameters()); this.callableStatementFactory.setResultSetType(getResultSetType()); this.callableStatementFactory.setUpdatableResults(isUpdatableResults()); this.callableStatementFactory.setNativeJdbcExtractor(getJdbcTemplate().getNativeJdbcExtractor()); onCompileInternal(); }
Example #25
Source File: SimpleJdbcCallTests.java From effectivejava with Apache License 2.0 | 5 votes |
@Test public void testAddInvoiceFuncWithoutMetaDataUsingArrayParams() throws Exception { initializeAddInvoiceWithoutMetaData(true); SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withFunctionName("add_invoice"); adder.declareParameters( new SqlOutParameter("return", Types.INTEGER), new SqlParameter("amount", Types.INTEGER), new SqlParameter("custid", Types.INTEGER)); Number newId = adder.executeFunction(Number.class, 1103, 3); assertEquals(4, newId.intValue()); verifyAddInvoiceWithoutMetaData(true); verify(connection, atLeastOnce()).close(); }
Example #26
Source File: SqlUpdateTests.java From effectivejava with Apache License 2.0 | 5 votes |
public MixedUpdater() { setSql(UPDATE_OBJECTS); setDataSource(dataSource); declareParameter(new SqlParameter(Types.NUMERIC)); declareParameter(new SqlParameter(Types.NUMERIC, 2)); declareParameter(new SqlParameter(Types.VARCHAR)); declareParameter(new SqlParameter(Types.BOOLEAN)); compile(); }
Example #27
Source File: CallMetaDataContextTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void testMatchParameterValuesAndSqlInOutParameters() throws Exception { final String TABLE = "customers"; final String USER = "me"; given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB"); given(databaseMetaData.getUserName()).willReturn(USER); given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true); List<SqlParameter> parameters = new ArrayList<>(); parameters.add(new SqlParameter("id", Types.NUMERIC)); parameters.add(new SqlInOutParameter("name", Types.NUMERIC)); parameters.add(new SqlOutParameter("customer_no", Types.NUMERIC)); MapSqlParameterSource parameterSource = new MapSqlParameterSource(); parameterSource.addValue("id", 1); parameterSource.addValue("name", "Sven"); parameterSource.addValue("customer_no", "12345XYZ"); context.setProcedureName(TABLE); context.initializeMetaData(dataSource); context.processParameters(parameters); Map<String, Object> inParameters = context.matchInParameterValuesWithCallParameters(parameterSource); assertEquals("Wrong number of matched in parameter values", 2, inParameters.size()); assertTrue("in parameter value missing", inParameters.containsKey("id")); assertTrue("in out parameter value missing", inParameters.containsKey("name")); assertTrue("out parameter value matched", !inParameters.containsKey("customer_no")); List<String> names = context.getOutParameterNames(); assertEquals("Wrong number of out parameters", 2, names.size()); List<SqlParameter> callParameters = context.getCallParameters(); assertEquals("Wrong number of call parameters", 3, callParameters.size()); }
Example #28
Source File: SqlUpdateTests.java From effectivejava with Apache License 2.0 | 5 votes |
public IntIntUpdater() { setSql(UPDATE_INT_INT); setDataSource(dataSource); declareParameter(new SqlParameter(Types.NUMERIC)); declareParameter(new SqlParameter(Types.NUMERIC)); compile(); }
Example #29
Source File: CallMetaDataContext.java From effectivejava with Apache License 2.0 | 5 votes |
/** * Create a ReturnResultSetParameter/SqlOutParameter depending on the support provided * by the JDBC driver used for the database in use. * @param parameterName the name of the parameter (also used as the name of the List returned in the output) * @param rowMapper a RowMapper implementation used to map the data returned in the result set * @return the appropriate SqlParameter */ public SqlParameter createReturnResultSetParameter(String parameterName, RowMapper<?> rowMapper) { if (this.metaDataProvider.isReturnResultSetSupported()) { return new SqlReturnResultSet(parameterName, rowMapper); } else { if (this.metaDataProvider.isRefCursorSupported()) { return new SqlOutParameter(parameterName, this.metaDataProvider.getRefCursorSqlType(), rowMapper); } else { throw new InvalidDataAccessApiUsageException("Return of a ResultSet from a stored procedure is not supported."); } } }
Example #30
Source File: StoredProcedureTests.java From spring-analysis-note with MIT License | 5 votes |
/** * Confirm no connection was used to get metadata. Does not use superclass replay * mechanism. */ @Test public void testStoredProcedureConfiguredViaJdbcTemplateWithCustomExceptionTranslator() throws Exception { given(callableStatement.execute()).willReturn(false); given(callableStatement.getUpdateCount()).willReturn(-1); given(callableStatement.getObject(2)).willReturn(5); given(connection.prepareCall("{call " + StoredProcedureConfiguredViaJdbcTemplate.SQL + "(?, ?)}") ).willReturn(callableStatement); class TestJdbcTemplate extends JdbcTemplate { int calls; @Override public Map<String, Object> call(CallableStatementCreator csc, List<SqlParameter> declaredParameters) throws DataAccessException { calls++; return super.call(csc, declaredParameters); } } TestJdbcTemplate t = new TestJdbcTemplate(); t.setDataSource(dataSource); // Will fail without the following, because we're not able to get a connection // from the DataSource here if we need to create an ExceptionTranslator t.setExceptionTranslator(new SQLStateSQLExceptionTranslator()); StoredProcedureConfiguredViaJdbcTemplate sp = new StoredProcedureConfiguredViaJdbcTemplate(t); assertEquals(5, sp.execute(11)); assertEquals(1, t.calls); verify(callableStatement).setObject(1, 11, Types.INTEGER); verify(callableStatement).registerOutParameter(2, Types.INTEGER); }