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.namedparam; 018 019import java.sql.PreparedStatement; 020import java.sql.SQLException; 021 022import org.springframework.jdbc.core.BatchPreparedStatementSetter; 023import org.springframework.jdbc.core.BatchUpdateUtils; 024import org.springframework.jdbc.core.JdbcOperations; 025 026/** 027 * Generic utility methods for working with JDBC batch statements using named parameters. 028 * Mainly for internal use within the framework. 029 * 030 * @author Thomas Risberg 031 * @author Juergen Hoeller 032 * @since 3.0 033 */ 034public class NamedParameterBatchUpdateUtils extends BatchUpdateUtils { 035 036 public static int[] executeBatchUpdateWithNamedParameters( 037 final ParsedSql parsedSql, final SqlParameterSource[] batchArgs, JdbcOperations jdbcOperations) { 038 039 if (batchArgs.length == 0) { 040 return new int[0]; 041 } 042 043 String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, batchArgs[0]); 044 return jdbcOperations.batchUpdate( 045 sqlToUse, 046 new BatchPreparedStatementSetter() { 047 @Override 048 public void setValues(PreparedStatement ps, int i) throws SQLException { 049 Object[] values = NamedParameterUtils.buildValueArray(parsedSql, batchArgs[i], null); 050 int[] columnTypes = NamedParameterUtils.buildSqlTypeArray(parsedSql, batchArgs[i]); 051 setStatementParameters(values, ps, columnTypes); 052 } 053 @Override 054 public int getBatchSize() { 055 return batchArgs.length; 056 } 057 }); 058 } 059 060}