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; 021import java.util.List; 022 023/** 024 * Generic utility methods for working with JDBC batch statements. 025 * Mainly for internal use within the framework. 026 * 027 * @author Thomas Risberg 028 * @author Juergen Hoeller 029 * @since 3.0 030 */ 031public abstract class BatchUpdateUtils { 032 033 public static int[] executeBatchUpdate( 034 String sql, final List<Object[]> batchArgs, final int[] columnTypes, JdbcOperations jdbcOperations) { 035 036 if (batchArgs.isEmpty()) { 037 return new int[0]; 038 } 039 040 return jdbcOperations.batchUpdate( 041 sql, 042 new BatchPreparedStatementSetter() { 043 @Override 044 public void setValues(PreparedStatement ps, int i) throws SQLException { 045 Object[] values = batchArgs.get(i); 046 setStatementParameters(values, ps, columnTypes); 047 } 048 @Override 049 public int getBatchSize() { 050 return batchArgs.size(); 051 } 052 }); 053 } 054 055 protected static void setStatementParameters(Object[] values, PreparedStatement ps, int[] columnTypes) 056 throws SQLException { 057 058 int colIndex = 0; 059 for (Object value : values) { 060 colIndex++; 061 if (value instanceof SqlParameterValue) { 062 SqlParameterValue paramValue = (SqlParameterValue) value; 063 StatementCreatorUtils.setParameterValue(ps, colIndex, paramValue, paramValue.getValue()); 064 } 065 else { 066 int colType; 067 if (columnTypes == null || columnTypes.length < colIndex) { 068 colType = SqlTypeValue.TYPE_UNKNOWN; 069 } 070 else { 071 colType = columnTypes[colIndex - 1]; 072 } 073 StatementCreatorUtils.setParameterValue(ps, colIndex, colType, value); 074 } 075 } 076 } 077 078}