View Javadoc
1   /*
2    * Copyright 2002-2013 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.jdbc.core;
18  
19  import java.sql.PreparedStatement;
20  import java.sql.SQLException;
21  
22  /**
23   * Simple adapter for {@link PreparedStatementSetter} that applies a given array of arguments.
24   *
25   * @author Juergen Hoeller
26   * @since 3.2.3
27   */
28  public class ArgumentPreparedStatementSetter implements PreparedStatementSetter, ParameterDisposer {
29  
30  	private final Object[] args;
31  
32  
33  	/**
34  	 * Create a new ArgPreparedStatementSetter for the given arguments.
35  	 * @param args the arguments to set
36  	 */
37  	public ArgumentPreparedStatementSetter(Object[] args) {
38  		this.args = args;
39  	}
40  
41  
42  	@Override
43  	public void setValues(PreparedStatement ps) throws SQLException {
44  		if (this.args != null) {
45  			for (int i = 0; i < this.args.length; i++) {
46  				Object arg = this.args[i];
47  				doSetValue(ps, i + 1, arg);
48  			}
49  		}
50  	}
51  
52  	/**
53  	 * Set the value for prepared statements specified parameter index using the passed in value.
54  	 * This method can be overridden by sub-classes if needed.
55  	 * @param ps the PreparedStatement
56  	 * @param parameterPosition index of the parameter position
57  	 * @param argValue the value to set
58  	 * @throws SQLException
59  	 */
60  	protected void doSetValue(PreparedStatement ps, int parameterPosition, Object argValue) throws SQLException {
61  		if (argValue instanceof SqlParameterValue) {
62  			SqlParameterValue paramValue = (SqlParameterValue) argValue;
63  			StatementCreatorUtils.setParameterValue(ps, parameterPosition, paramValue, paramValue.getValue());
64  		}
65  		else {
66  			StatementCreatorUtils.setParameterValue(ps, parameterPosition, SqlTypeValue.TYPE_UNKNOWN, argValue);
67  		}
68  	}
69  
70  	@Override
71  	public void cleanupParameters() {
72  		StatementCreatorUtils.cleanupParameters(this.args);
73  	}
74  
75  }