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 022import org.springframework.lang.Nullable; 023 024/** 025 * Simple adapter for {@link PreparedStatementSetter} that applies a given array of arguments. 026 * 027 * @author Juergen Hoeller 028 * @since 3.2.3 029 */ 030public class ArgumentPreparedStatementSetter implements PreparedStatementSetter, ParameterDisposer { 031 032 @Nullable 033 private final Object[] args; 034 035 036 /** 037 * Create a new ArgPreparedStatementSetter for the given arguments. 038 * @param args the arguments to set 039 */ 040 public ArgumentPreparedStatementSetter(@Nullable Object[] args) { 041 this.args = args; 042 } 043 044 045 @Override 046 public void setValues(PreparedStatement ps) throws SQLException { 047 if (this.args != null) { 048 for (int i = 0; i < this.args.length; i++) { 049 Object arg = this.args[i]; 050 doSetValue(ps, i + 1, arg); 051 } 052 } 053 } 054 055 /** 056 * Set the value for prepared statements specified parameter index using the passed in value. 057 * This method can be overridden by sub-classes if needed. 058 * @param ps the PreparedStatement 059 * @param parameterPosition index of the parameter position 060 * @param argValue the value to set 061 * @throws SQLException if thrown by PreparedStatement methods 062 */ 063 protected void doSetValue(PreparedStatement ps, int parameterPosition, Object argValue) throws SQLException { 064 if (argValue instanceof SqlParameterValue) { 065 SqlParameterValue paramValue = (SqlParameterValue) argValue; 066 StatementCreatorUtils.setParameterValue(ps, parameterPosition, paramValue, paramValue.getValue()); 067 } 068 else { 069 StatementCreatorUtils.setParameterValue(ps, parameterPosition, SqlTypeValue.TYPE_UNKNOWN, argValue); 070 } 071 } 072 073 @Override 074 public void cleanupParameters() { 075 StatementCreatorUtils.cleanupParameters(this.args); 076 } 077 078}