RdbmsOperation.java 16.3 KB
Newer Older
A
Arjen Poutsma 已提交
1
/*
N
nkjackzhang 已提交
2
 * Copyright 2002-2018 the original author or authors.
A
Arjen Poutsma 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.jdbc.object;

import java.sql.ResultSet;
import java.sql.Types;
J
Juergen Hoeller 已提交
21 22 23 24 25
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
A
Arjen Poutsma 已提交
26 27 28 29 30 31 32 33 34
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlParameter;
35
import org.springframework.lang.Nullable;
36
import org.springframework.util.Assert;
A
Arjen Poutsma 已提交
37 38 39 40 41 42 43 44

/**
 * An "RDBMS operation" is a multi-threaded, reusable object representing a query,
 * update, or stored procedure call. An RDBMS operation is <b>not</b> a command,
 * as a command is not reusable. However, execute methods may take commands as
 * arguments. Subclasses should be JavaBeans, allowing easy configuration.
 *
 * <p>This class and subclasses throw runtime exceptions, defined in the
N
nkjackzhang 已提交
45
 * {@code org.springframework.dao} package (and as thrown by the
46
 * {@code org.springframework.jdbc.core} package, which the classes
A
Arjen Poutsma 已提交
47 48 49 50
 * in this package use under the hood to perform raw JDBC operations).
 *
 * <p>Subclasses should set SQL and add parameters before invoking the
 * {@link #compile()} method. The order in which parameters are added is
51
 * significant. The appropriate {@code execute} or {@code update}
A
Arjen Poutsma 已提交
52 53 54 55 56 57 58 59 60 61 62
 * method can then be invoked.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @see SqlQuery
 * @see SqlUpdate
 * @see StoredProcedure
 * @see org.springframework.jdbc.core.JdbcTemplate
 */
public abstract class RdbmsOperation implements InitializingBean {

P
Phillip Webb 已提交
63
	/** Logger available to subclasses. */
A
Arjen Poutsma 已提交
64 65
	protected final Log logger = LogFactory.getLog(getClass());

P
Phillip Webb 已提交
66
	/** Lower-level class used to execute SQL. */
A
Arjen Poutsma 已提交
67 68 69 70 71 72 73
	private JdbcTemplate jdbcTemplate = new JdbcTemplate();

	private int resultSetType = ResultSet.TYPE_FORWARD_ONLY;

	private boolean updatableResults = false;

	private boolean returnGeneratedKeys = false;
74

75 76
	@Nullable
	private String[] generatedKeysColumnNames;
A
Arjen Poutsma 已提交
77

78
	@Nullable
A
Arjen Poutsma 已提交
79 80
	private String sql;

81
	private final List<SqlParameter> declaredParameters = new LinkedList<>();
A
Arjen Poutsma 已提交
82 83 84 85 86 87

	/**
	 * Has this operation been compiled? Compilation means at
	 * least checking that a DataSource and sql have been provided,
	 * but subclasses may also implement their own custom validation.
	 */
88
	private volatile boolean compiled;
89 90


A
Arjen Poutsma 已提交
91
	/**
92 93 94 95
	 * An alternative to the more commonly used {@link #setDataSource} when you want to
	 * use the same {@link JdbcTemplate} in multiple {@code RdbmsOperations}. This is
	 * appropriate if the {@code JdbcTemplate} has special configuration such as a
	 * {@link org.springframework.jdbc.support.SQLExceptionTranslator} to be reused.
A
Arjen Poutsma 已提交
96 97 98 99 100 101
	 */
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	/**
102
	 * Return the {@link JdbcTemplate} used by this operation object.
A
Arjen Poutsma 已提交
103 104 105 106 107 108
	 */
	public JdbcTemplate getJdbcTemplate() {
		return this.jdbcTemplate;
	}

	/**
109
	 * Set the JDBC {@link DataSource} to obtain connections from.
A
Arjen Poutsma 已提交
110 111 112 113 114 115 116 117 118 119 120
	 * @see org.springframework.jdbc.core.JdbcTemplate#setDataSource
	 */
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate.setDataSource(dataSource);
	}

	/**
	 * Set the fetch size for this RDBMS operation. This is important for processing
	 * large result sets: Setting this higher than the default value will increase
	 * processing speed at the cost of memory consumption; setting this lower can
	 * avoid transferring row data that will never be read by the application.
121
	 * <p>Default is -1, indicating to use the driver's default.
A
Arjen Poutsma 已提交
122 123 124 125 126 127 128 129 130 131
	 * @see org.springframework.jdbc.core.JdbcTemplate#setFetchSize
	 */
	public void setFetchSize(int fetchSize) {
		this.jdbcTemplate.setFetchSize(fetchSize);
	}

	/**
	 * Set the maximum number of rows for this RDBMS operation. This is important
	 * for processing subsets of large result sets, avoiding to read and hold
	 * the entire result set in the database or in the JDBC driver.
132
	 * <p>Default is -1, indicating to use the driver's default.
A
Arjen Poutsma 已提交
133 134 135 136 137 138 139 140
	 * @see org.springframework.jdbc.core.JdbcTemplate#setMaxRows
	 */
	public void setMaxRows(int maxRows) {
		this.jdbcTemplate.setMaxRows(maxRows);
	}

	/**
	 * Set the query timeout for statements that this RDBMS operation executes.
141
	 * <p>Default is -1, indicating to use the JDBC driver's default.
A
Arjen Poutsma 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
	 * <p>Note: Any timeout specified here will be overridden by the remaining
	 * transaction timeout when executing within a transaction that has a
	 * timeout specified at the transaction level.
	 */
	public void setQueryTimeout(int queryTimeout) {
		this.jdbcTemplate.setQueryTimeout(queryTimeout);
	}

	/**
	 * Set whether to use statements that return a specific type of ResultSet.
	 * @param resultSetType the ResultSet type
	 * @see java.sql.ResultSet#TYPE_FORWARD_ONLY
	 * @see java.sql.ResultSet#TYPE_SCROLL_INSENSITIVE
	 * @see java.sql.ResultSet#TYPE_SCROLL_SENSITIVE
	 * @see java.sql.Connection#prepareStatement(String, int, int)
	 */
	public void setResultSetType(int resultSetType) {
		this.resultSetType = resultSetType;
	}

	/**
	 * Return whether statements will return a specific type of ResultSet.
	 */
	public int getResultSetType() {
		return this.resultSetType;
	}

	/**
	 * Set whether to use statements that are capable of returning
	 * updatable ResultSets.
	 * @see java.sql.Connection#prepareStatement(String, int, int)
	 */
	public void setUpdatableResults(boolean updatableResults) {
		if (isCompiled()) {
			throw new InvalidDataAccessApiUsageException(
					"The updateableResults flag must be set before the operation is compiled");
		}
		this.updatableResults = updatableResults;
	}

	/**
	 * Return whether statements will return updatable ResultSets.
	 */
	public boolean isUpdatableResults() {
		return this.updatableResults;
	}

	/**
	 * Set whether prepared statements should be capable of returning
	 * auto-generated keys.
	 * @see java.sql.Connection#prepareStatement(String, int)
	 */
	public void setReturnGeneratedKeys(boolean returnGeneratedKeys) {
		if (isCompiled()) {
			throw new InvalidDataAccessApiUsageException(
					"The returnGeneratedKeys flag must be set before the operation is compiled");
		}
		this.returnGeneratedKeys = returnGeneratedKeys;
	}

	/**
	 * Return whether statements should be capable of returning
	 * auto-generated keys.
	 */
	public boolean isReturnGeneratedKeys() {
		return this.returnGeneratedKeys;
	}

	/**
	 * Set the column names of the auto-generated keys.
	 * @see java.sql.Connection#prepareStatement(String, String[])
	 */
214
	public void setGeneratedKeysColumnNames(@Nullable String... names) {
A
Arjen Poutsma 已提交
215 216 217 218 219 220 221 222 223 224
		if (isCompiled()) {
			throw new InvalidDataAccessApiUsageException(
					"The column names for the generated keys must be set before the operation is compiled");
		}
		this.generatedKeysColumnNames = names;
	}

	/**
	 * Return the column names of the auto generated keys.
	 */
225
	@Nullable
A
Arjen Poutsma 已提交
226 227 228 229 230 231 232
	public String[] getGeneratedKeysColumnNames() {
		return this.generatedKeysColumnNames;
	}

	/**
	 * Set the SQL executed by this operation.
	 */
233
	public void setSql(@Nullable String sql) {
A
Arjen Poutsma 已提交
234 235 236 237
		this.sql = sql;
	}

	/**
238 239
	 * Subclasses can override this to supply dynamic SQL if they wish, but SQL is
	 * normally set by calling the {@link #setSql} method or in a subclass constructor.
A
Arjen Poutsma 已提交
240
	 */
241
	@Nullable
A
Arjen Poutsma 已提交
242 243 244 245
	public String getSql() {
		return this.sql;
	}

246 247 248 249 250 251 252 253 254 255 256
	/**
	 * Resolve the configured SQL for actual use.
	 * @return the SQL (never {@code null})
	 * @since 5.0
	 */
	protected String resolveSql() {
		String sql = getSql();
		Assert.state(sql != null, "No SQL set");
		return sql;
	}

A
Arjen Poutsma 已提交
257 258
	/**
	 * Add anonymous parameters, specifying only their SQL types
259
	 * as defined in the {@code java.sql.Types} class.
A
Arjen Poutsma 已提交
260 261 262
	 * <p>Parameter ordering is significant. This method is an alternative
	 * to the {@link #declareParameter} method, which should normally be preferred.
	 * @param types array of SQL types as defined in the
263
	 * {@code java.sql.Types} class
A
Arjen Poutsma 已提交
264 265
	 * @throws InvalidDataAccessApiUsageException if the operation is already compiled
	 */
266
	public void setTypes(@Nullable int[] types) throws InvalidDataAccessApiUsageException {
A
Arjen Poutsma 已提交
267 268 269 270
		if (isCompiled()) {
			throw new InvalidDataAccessApiUsageException("Cannot add parameters once query is compiled");
		}
		if (types != null) {
J
Juergen Hoeller 已提交
271 272
			for (int type : types) {
				declareParameter(new SqlParameter(type));
A
Arjen Poutsma 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
			}
		}
	}

	/**
	 * Declare a parameter for this operation.
	 * <p>The order in which this method is called is significant when using
	 * positional parameters. It is not significant when using named parameters
	 * with named SqlParameter objects here; it remains significant when using
	 * named parameters in combination with unnamed SqlParameter objects here.
	 * @param param the SqlParameter to add. This will specify SQL type and (optionally)
	 * the parameter's name. Note that you typically use the {@link SqlParameter} class
	 * itself here, not any of its subclasses.
	 * @throws InvalidDataAccessApiUsageException if the operation is already compiled,
	 * and hence cannot be configured further
	 */
	public void declareParameter(SqlParameter param) throws InvalidDataAccessApiUsageException {
		if (isCompiled()) {
			throw new InvalidDataAccessApiUsageException("Cannot add parameters once the query is compiled");
		}
		this.declaredParameters.add(param);
	}

	/**
297
	 * Add one or more declared parameters. Used for configuring this operation
A
Arjen Poutsma 已提交
298 299
	 * when used in a bean factory.  Each parameter will specify SQL type and (optionally)
	 * the parameter's name.
P
Phillip Webb 已提交
300
	 * @param parameters an array containing the declared {@link SqlParameter} objects
A
Arjen Poutsma 已提交
301 302
	 * @see #declaredParameters
	 */
303
	public void setParameters(SqlParameter... parameters) {
A
Arjen Poutsma 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
		if (isCompiled()) {
			throw new InvalidDataAccessApiUsageException("Cannot add parameters once the query is compiled");
		}
		for (int i = 0; i < parameters.length; i++) {
			if (parameters[i] != null) {
				this.declaredParameters.add(parameters[i]);
			}
			else {
				throw new InvalidDataAccessApiUsageException("Cannot add parameter at index " + i + " from " +
						Arrays.asList(parameters) + " since it is 'null'");
			}
		}
	}

	/**
	 * Return a list of the declared {@link SqlParameter} objects.
	 */
J
Juergen Hoeller 已提交
321
	protected List<SqlParameter> getDeclaredParameters() {
A
Arjen Poutsma 已提交
322 323 324 325 326 327 328
		return this.declaredParameters;
	}


	/**
	 * Ensures compilation if used in a bean factory.
	 */
329
	@Override
A
Arjen Poutsma 已提交
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
	public void afterPropertiesSet() {
		compile();
	}

	/**
	 * Compile this query.
	 * Ignores subsequent attempts to compile.
	 * @throws InvalidDataAccessApiUsageException if the object hasn't
	 * been correctly initialized, for example if no DataSource has been provided
	 */
	public final void compile() throws InvalidDataAccessApiUsageException {
		if (!isCompiled()) {
			if (getSql() == null) {
				throw new InvalidDataAccessApiUsageException("Property 'sql' is required");
			}

			try {
				this.jdbcTemplate.afterPropertiesSet();
			}
			catch (IllegalArgumentException ex) {
				throw new InvalidDataAccessApiUsageException(ex.getMessage());
351 352
			}

A
Arjen Poutsma 已提交
353 354 355 356 357 358 359 360 361 362 363 364 365
			compileInternal();
			this.compiled = true;

			if (logger.isDebugEnabled()) {
				logger.debug("RdbmsOperation with SQL [" + getSql() + "] compiled");
			}
		}
	}

	/**
	 * Is this operation "compiled"? Compilation, as in JDO,
	 * means that the operation is fully configured, and ready to use.
	 * The exact meaning of compilation will vary between subclasses.
366
	 * @return whether this operation is compiled and ready to use
A
Arjen Poutsma 已提交
367 368 369 370 371 372 373 374
	 */
	public boolean isCompiled() {
		return this.compiled;
	}

	/**
	 * Check whether this operation has been compiled already;
	 * lazily compile it if not already compiled.
375
	 * <p>Automatically called by {@code validateParameters}.
A
Arjen Poutsma 已提交
376 377 378 379 380 381 382 383 384 385 386
	 * @see #validateParameters
	 */
	protected void checkCompiled() {
		if (!isCompiled()) {
			logger.debug("SQL operation not compiled before execution - invoking compile");
			compile();
		}
	}

	/**
	 * Validate the parameters passed to an execute method based on declared parameters.
387 388 389
	 * Subclasses should invoke this method before every {@code executeQuery()}
	 * or {@code update()} method.
	 * @param parameters parameters supplied (may be {@code null})
A
Arjen Poutsma 已提交
390 391
	 * @throws InvalidDataAccessApiUsageException if the parameters are invalid
	 */
392
	protected void validateParameters(@Nullable Object[] parameters) throws InvalidDataAccessApiUsageException {
A
Arjen Poutsma 已提交
393 394
		checkCompiled();
		int declaredInParameters = 0;
J
Juergen Hoeller 已提交
395
		for (SqlParameter param : this.declaredParameters) {
A
Arjen Poutsma 已提交
396 397 398 399 400 401 402 403 404 405 406 407 408 409
			if (param.isInputValueProvided()) {
				if (!supportsLobParameters() &&
						(param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) {
					throw new InvalidDataAccessApiUsageException(
							"BLOB or CLOB parameters are not allowed for this kind of operation");
				}
				declaredInParameters++;
			}
		}
		validateParameterCount((parameters != null ? parameters.length : 0), declaredInParameters);
	}

	/**
	 * Validate the named parameters passed to an execute method based on declared parameters.
410 411
	 * Subclasses should invoke this method before every {@code executeQuery()} or
	 * {@code update()} method.
412
	 * @param parameters parameter Map supplied (may be {@code null})
A
Arjen Poutsma 已提交
413 414
	 * @throws InvalidDataAccessApiUsageException if the parameters are invalid
	 */
415
	protected void validateNamedParameters(@Nullable Map<String, ?> parameters) throws InvalidDataAccessApiUsageException {
A
Arjen Poutsma 已提交
416
		checkCompiled();
P
Phillip Webb 已提交
417
		Map<String, ?> paramsToUse = (parameters != null ? parameters : Collections.<String, Object> emptyMap());
A
Arjen Poutsma 已提交
418
		int declaredInParameters = 0;
J
Juergen Hoeller 已提交
419
		for (SqlParameter param : this.declaredParameters) {
A
Arjen Poutsma 已提交
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
			if (param.isInputValueProvided()) {
				if (!supportsLobParameters() &&
						(param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) {
					throw new InvalidDataAccessApiUsageException(
							"BLOB or CLOB parameters are not allowed for this kind of operation");
				}
				if (param.getName() != null && !paramsToUse.containsKey(param.getName())) {
					throw new InvalidDataAccessApiUsageException("The parameter named '" + param.getName() +
							"' was not among the parameters supplied: " + paramsToUse.keySet());
				}
				declaredInParameters++;
			}
		}
		validateParameterCount(paramsToUse.size(), declaredInParameters);
	}

	/**
	 * Validate the given parameter count against the given declared parameters.
	 * @param suppliedParamCount the number of actual parameters given
	 * @param declaredInParamCount the number of input parameters declared
	 */
	private void validateParameterCount(int suppliedParamCount, int declaredInParamCount) {
		if (suppliedParamCount < declaredInParamCount) {
			throw new InvalidDataAccessApiUsageException(suppliedParamCount + " parameters were supplied, but " +
					declaredInParamCount + " in parameters were declared in class [" + getClass().getName() + "]");
		}
		if (suppliedParamCount > this.declaredParameters.size() && !allowsUnusedParameters()) {
			throw new InvalidDataAccessApiUsageException(suppliedParamCount + " parameters were supplied, but " +
					declaredInParamCount + " parameters were declared in class [" + getClass().getName() + "]");
		}
	}


	/**
	 * Subclasses must implement this template method to perform their own compilation.
	 * Invoked after this base class's compilation is complete.
	 * <p>Subclasses can assume that SQL and a DataSource have been supplied.
	 * @throws InvalidDataAccessApiUsageException if the subclass hasn't been
	 * properly configured
	 */
	protected abstract void compileInternal() throws InvalidDataAccessApiUsageException;

	/**
	 * Return whether BLOB/CLOB parameters are supported for this kind of operation.
464
	 * <p>The default is {@code true}.
A
Arjen Poutsma 已提交
465 466 467 468 469 470 471 472
	 */
	protected boolean supportsLobParameters() {
		return true;
	}

	/**
	 * Return whether this operation accepts additional parameters that are
	 * given but not actually used. Applies in particular to parameter Maps.
473
	 * <p>The default is {@code false}.
A
Arjen Poutsma 已提交
474 475 476 477 478 479 480
	 * @see StoredProcedure
	 */
	protected boolean allowsUnusedParameters() {
		return false;
	}

}