|
| 1 | +/* |
| 2 | + * Copyright 2022 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 | + * https://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 | +package org.springframework.data.jdbc.core.convert; |
| 17 | + |
| 18 | +import org.springframework.jdbc.core.BatchPreparedStatementSetter; |
| 19 | +import org.springframework.jdbc.core.ColumnMapRowMapper; |
| 20 | +import org.springframework.jdbc.core.JdbcOperations; |
| 21 | +import org.springframework.jdbc.core.PreparedStatementCallback; |
| 22 | +import org.springframework.jdbc.core.PreparedStatementCreator; |
| 23 | +import org.springframework.jdbc.core.PreparedStatementCreatorFactory; |
| 24 | +import org.springframework.jdbc.core.RowMapperResultSetExtractor; |
| 25 | +import org.springframework.jdbc.core.SqlParameter; |
| 26 | +import org.springframework.jdbc.core.namedparam.NamedParameterUtils; |
| 27 | +import org.springframework.jdbc.core.namedparam.ParsedSql; |
| 28 | +import org.springframework.jdbc.core.namedparam.SqlParameterSource; |
| 29 | +import org.springframework.jdbc.support.JdbcUtils; |
| 30 | +import org.springframework.jdbc.support.KeyHolder; |
| 31 | +import org.springframework.lang.Nullable; |
| 32 | +import org.springframework.util.Assert; |
| 33 | + |
| 34 | +import java.sql.PreparedStatement; |
| 35 | +import java.sql.ResultSet; |
| 36 | +import java.sql.SQLException; |
| 37 | +import java.util.ArrayList; |
| 38 | +import java.util.List; |
| 39 | +import java.util.Map; |
| 40 | + |
| 41 | +/** |
| 42 | + * Counterpart to {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations} containing |
| 43 | + * methods for performing batch updates with generated keys. |
| 44 | + * |
| 45 | + * @author Chirag Tailor |
| 46 | + * @since 2.4 |
| 47 | + */ |
| 48 | +public class BatchJdbcOperations { |
| 49 | + private final JdbcOperations jdbcOperations; |
| 50 | + |
| 51 | + public BatchJdbcOperations(JdbcOperations jdbcOperations) { |
| 52 | + this.jdbcOperations = jdbcOperations; |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Execute a batch using the supplied SQL statement with the batch of supplied arguments, |
| 57 | + * returning generated keys. |
| 58 | + * @param sql the SQL statement to execute |
| 59 | + * @param batchArgs the array of {@link SqlParameterSource} containing the batch of |
| 60 | + * arguments for the query |
| 61 | + * @param generatedKeyHolder a {@link KeyHolder} that will hold the generated keys |
| 62 | + * @return an array containing the numbers of rows affected by each update in the batch |
| 63 | + * (may also contain special JDBC-defined negative values for affected rows such as |
| 64 | + * {@link java.sql.Statement#SUCCESS_NO_INFO}/{@link java.sql.Statement#EXECUTE_FAILED}) |
| 65 | + * @throws org.springframework.dao.DataAccessException if there is any problem issuing the update |
| 66 | + * @see org.springframework.jdbc.support.GeneratedKeyHolder |
| 67 | + * @since 2.4 |
| 68 | + */ |
| 69 | + int[] batchUpdate(String sql, SqlParameterSource[] batchArgs, KeyHolder generatedKeyHolder) { |
| 70 | + return batchUpdate(sql, batchArgs, generatedKeyHolder, null); |
| 71 | + } |
| 72 | + |
| 73 | + /** |
| 74 | + * Execute a batch using the supplied SQL statement with the batch of supplied arguments, |
| 75 | + * returning generated keys. |
| 76 | + * @param sql the SQL statement to execute |
| 77 | + * @param batchArgs the array of {@link SqlParameterSource} containing the batch of |
| 78 | + * arguments for the query |
| 79 | + * @param generatedKeyHolder a {@link KeyHolder} that will hold the generated keys |
| 80 | + * @param keyColumnNames names of the columns that will have keys generated for them |
| 81 | + * @return an array containing the numbers of rows affected by each update in the batch |
| 82 | + * (may also contain special JDBC-defined negative values for affected rows such as |
| 83 | + * {@link java.sql.Statement#SUCCESS_NO_INFO}/{@link java.sql.Statement#EXECUTE_FAILED}) |
| 84 | + * @throws org.springframework.dao.DataAccessException if there is any problem issuing the update |
| 85 | + * @see org.springframework.jdbc.support.GeneratedKeyHolder |
| 86 | + * @since 2.4 |
| 87 | + */ |
| 88 | + int[] batchUpdate(String sql, SqlParameterSource[] batchArgs, KeyHolder generatedKeyHolder, |
| 89 | + @Nullable String[] keyColumnNames) { |
| 90 | + |
| 91 | + if (batchArgs.length == 0) { |
| 92 | + return new int[0]; |
| 93 | + } |
| 94 | + |
| 95 | + ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); |
| 96 | + SqlParameterSource paramSource = batchArgs[0]; |
| 97 | + String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource); |
| 98 | + List<SqlParameter> declaredParameters = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource); |
| 99 | + PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlToUse, declaredParameters); |
| 100 | + if (keyColumnNames != null) { |
| 101 | + pscf.setGeneratedKeysColumnNames(keyColumnNames); |
| 102 | + } else { |
| 103 | + pscf.setReturnGeneratedKeys(true); |
| 104 | + } |
| 105 | + Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, null); |
| 106 | + PreparedStatementCreator psc = pscf.newPreparedStatementCreator(params); |
| 107 | + BatchPreparedStatementSetter bpss = new BatchPreparedStatementSetter() { |
| 108 | + @Override |
| 109 | + public void setValues(PreparedStatement ps, int i) throws SQLException { |
| 110 | + Object[] values = NamedParameterUtils.buildValueArray(parsedSql, batchArgs[i], null); |
| 111 | + pscf.newPreparedStatementSetter(values).setValues(ps); |
| 112 | + } |
| 113 | + |
| 114 | + @Override |
| 115 | + public int getBatchSize() { |
| 116 | + return batchArgs.length; |
| 117 | + } |
| 118 | + }; |
| 119 | + PreparedStatementCallback<int[]> preparedStatementCallback = ps -> { |
| 120 | + int batchSize = bpss.getBatchSize(); |
| 121 | + generatedKeyHolder.getKeyList().clear(); |
| 122 | + if (JdbcUtils.supportsBatchUpdates(ps.getConnection())) { |
| 123 | + for (int i = 0; i < batchSize; i++) { |
| 124 | + bpss.setValues(ps, i); |
| 125 | + ps.addBatch(); |
| 126 | + } |
| 127 | + int[] results = ps.executeBatch(); |
| 128 | + storeGeneratedKeys(generatedKeyHolder, ps); |
| 129 | + return results; |
| 130 | + } else { |
| 131 | + List<Integer> rowsAffected = new ArrayList<>(); |
| 132 | + for (int i = 0; i < batchSize; i++) { |
| 133 | + bpss.setValues(ps, i); |
| 134 | + rowsAffected.add(ps.executeUpdate()); |
| 135 | + storeGeneratedKeys(generatedKeyHolder, ps); |
| 136 | + } |
| 137 | + int[] rowsAffectedArray = new int[rowsAffected.size()]; |
| 138 | + for (int i = 0; i < rowsAffectedArray.length; i++) { |
| 139 | + rowsAffectedArray[i] = rowsAffected.get(i); |
| 140 | + } |
| 141 | + return rowsAffectedArray; |
| 142 | + } |
| 143 | + }; |
| 144 | + int[] result = jdbcOperations.execute(psc, preparedStatementCallback); |
| 145 | + Assert.state(result != null, "No result array"); |
| 146 | + return result; |
| 147 | + } |
| 148 | + |
| 149 | + private void storeGeneratedKeys(KeyHolder generatedKeyHolder, PreparedStatement ps) throws SQLException { |
| 150 | + |
| 151 | + List<Map<String, Object>> generatedKeys = generatedKeyHolder.getKeyList(); |
| 152 | + ResultSet keys = ps.getGeneratedKeys(); |
| 153 | + if (keys != null) { |
| 154 | + try { |
| 155 | + RowMapperResultSetExtractor<Map<String, Object>> rse = |
| 156 | + new RowMapperResultSetExtractor<>(new ColumnMapRowMapper(), 1); |
| 157 | + //noinspection ConstantConditions |
| 158 | + generatedKeys.addAll(rse.extractData(keys)); |
| 159 | + } |
| 160 | + finally { |
| 161 | + JdbcUtils.closeResultSet(keys); |
| 162 | + } |
| 163 | + } |
| 164 | + } |
| 165 | +} |
0 commit comments