001/* 002 * Copyright 2002-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.jdbc.core; 018 019import java.sql.PreparedStatement; 020import java.sql.SQLException; 021 022/** 023 * Simple adapter for {@link PreparedStatementSetter} that applies a given array of arguments. 024 * 025 * @author Juergen Hoeller 026 * @since 3.2.3 027 */ 028public class ArgumentPreparedStatementSetter implements PreparedStatementSetter, ParameterDisposer { 029 030 private final Object[] args; 031 032 033 /** 034 * Create a new ArgPreparedStatementSetter for the given arguments. 035 * @param args the arguments to set 036 */ 037 public ArgumentPreparedStatementSetter(Object[] args) { 038 this.args = args; 039 } 040 041 042 @Override 043 public void setValues(PreparedStatement ps) throws SQLException { 044 if (this.args != null) { 045 for (int i = 0; i < this.args.length; i++) { 046 Object arg = this.args[i]; 047 doSetValue(ps, i + 1, arg); 048 } 049 } 050 } 051 052 /** 053 * Set the value for prepared statements specified parameter index using the passed in value. 054 * This method can be overridden by sub-classes if needed. 055 * @param ps the PreparedStatement 056 * @param parameterPosition index of the parameter position 057 * @param argValue the value to set 058 * @throws SQLException if thrown by PreparedStatement methods 059 */ 060 protected void doSetValue(PreparedStatement ps, int parameterPosition, Object argValue) throws SQLException { 061 if (argValue instanceof SqlParameterValue) { 062 SqlParameterValue paramValue = (SqlParameterValue) argValue; 063 StatementCreatorUtils.setParameterValue(ps, parameterPosition, paramValue, paramValue.getValue()); 064 } 065 else { 066 StatementCreatorUtils.setParameterValue(ps, parameterPosition, SqlTypeValue.TYPE_UNKNOWN, argValue); 067 } 068 } 069 070 @Override 071 public void cleanupParameters() { 072 StatementCreatorUtils.cleanupParameters(this.args); 073 } 074 075}