Class JdbcTemplate
- All Implemented Interfaces:
InitializingBean
,JdbcOperations
JdbcClient
as of 6.1.
This class simplifies the use of JDBC and helps to avoid common errors.
It executes core JDBC workflow, leaving application code to provide SQL
and extract results. This class executes SQL queries or updates, initiating
iteration over ResultSets and catching JDBC exceptions and translating
them to the common org.springframework.dao
exception hierarchy.
Code using this class need only implement callback interfaces, giving
them a clearly defined contract. The PreparedStatementCreator
callback
interface creates a prepared statement given a Connection, providing SQL and
any necessary parameters. The ResultSetExtractor
interface extracts
values from a ResultSet. See also PreparedStatementSetter
and
RowMapper
for two popular alternative callback interfaces.
An instance of this template class is thread-safe once configured. Can be used within a service implementation via direct instantiation with a DataSource reference, or get prepared in an application context and given to services as bean reference. Note: The DataSource should always be configured as a bean in the application context, in the first case given to the service directly, in the second case to the prepared template.
Because this class is parameterizable by the callback interfaces and
the SQLExceptionTranslator
interface, there should be no need to subclass it.
All SQL operations performed by this class are logged at debug level, using "org.springframework.jdbc.core.JdbcTemplate" as log category.
NOTE: As of 6.1, there is a unified JDBC access facade available in
the form of JdbcClient
.
JdbcClient
provides a fluent API style for common JDBC queries/updates
with flexible use of indexed or named parameters. It delegates to a
JdbcTemplate
/NamedParameterJdbcTemplate
for actual execution.
- Since:
- May 3, 2001
- Author:
- Rod Johnson, Juergen Hoeller, Thomas Risberg
- See Also:
-
Field Summary
Fields inherited from class org.springframework.jdbc.support.JdbcAccessor
logger
-
Constructor Summary
ConstructorDescriptionConstruct a new JdbcTemplate for bean usage.JdbcTemplate
(DataSource dataSource) Construct a new JdbcTemplate, given a DataSource to obtain connections from.JdbcTemplate
(DataSource dataSource, boolean lazyInit) Construct a new JdbcTemplate, given a DataSource to obtain connections from. -
Method Summary
Modifier and TypeMethodDescriptionprotected void
Prepare the given JDBC Statement (or PreparedStatement or CallableStatement), applying statement settings such as fetch size, max rows, and query timeout.int[]
batchUpdate
(String... sql) Issue multiple SQL updates on a single JDBC Statement using batching.<T> int[][]
batchUpdate
(String sql, Collection<T> batchArgs, int batchSize, ParameterizedPreparedStatementSetter<T> pss) Execute multiple batches using the supplied SQL statement with the collect of supplied arguments.int[]
batchUpdate
(String sql, List<Object[]> batchArgs) Execute a batch using the supplied SQL statement with the batch of supplied arguments.int[]
batchUpdate
(String sql, List<Object[]> batchArgs, int[] argTypes) Execute a batch using the supplied SQL statement with the batch of supplied arguments.int[]
batchUpdate
(String sql, BatchPreparedStatementSetter pss) Issue multiple update statements on a single PreparedStatement, using batch updates and a BatchPreparedStatementSetter to set values.int[]
batchUpdate
(PreparedStatementCreator psc, BatchPreparedStatementSetter pss, KeyHolder generatedKeyHolder) Issue multiple update statements on a single PreparedStatement, using batch updates and a BatchPreparedStatementSetter to set values.call
(CallableStatementCreator csc, List<SqlParameter> declaredParameters) Execute an SQL call using a CallableStatementCreator to provide SQL and any required parameters.protected Connection
Create a close-suppressing proxy for the given JDBC Connection.Create a Map instance to be used as the results map.void
Issue a single SQL execute, typically a DDL statement.<T> T
execute
(String callString, CallableStatementCallback<T> action) Execute a JDBC data access operation, implemented as callback action working on a JDBC CallableStatement.<T> T
execute
(String sql, PreparedStatementCallback<T> action) Execute a JDBC data access operation, implemented as callback action working on a JDBC PreparedStatement.<T> T
execute
(CallableStatementCreator csc, CallableStatementCallback<T> action) Execute a JDBC data access operation, implemented as callback action working on a JDBC CallableStatement.<T> T
execute
(ConnectionCallback<T> action) Execute a JDBC data access operation, implemented as callback action working on a JDBC Connection.<T> T
execute
(PreparedStatementCreator psc, PreparedStatementCallback<T> action) Execute a JDBC data access operation, implemented as callback action working on a JDBC PreparedStatement.<T> T
execute
(StatementCallback<T> action) Execute a JDBC data access operation, implemented as callback action working on a JDBC Statement.extractOutputParameters
(CallableStatement cs, List<SqlParameter> parameters) Extract output parameters from the completed stored procedure.extractReturnedResults
(CallableStatement cs, List<SqlParameter> updateCountParameters, List<SqlParameter> resultSetParameters, int updateCount) Extract returned ResultSets from the completed stored procedure.Create a new RowMapper for reading columns as key-value pairs.int
Return the fetch size specified for this JdbcTemplate.int
Return the maximum number of rows specified for this JdbcTemplate.int
Return the query timeout for statements that this JdbcTemplate executes.protected <T> RowMapper<T>
getSingleColumnRowMapper
(Class<T> requiredType) Create a new RowMapper for reading result objects from a single column.protected void
handleWarnings
(SQLWarning warning) Throw aSQLWarningException
if encountering an actual warning.protected void
handleWarnings
(Statement stmt) Handle the warnings for the given JDBC statement, if any.protected void
handleWarnings
(Statement stmt, SQLException ex) Handle warnings before propagating a primarySQLException
from executing the given statement.boolean
Return whether we ignore SQLWarnings.boolean
Return whether execution of a CallableStatement will return the results in a Map that uses case-insensitive names for the parameters.boolean
Return whether results processing should be skipped.boolean
Return whether undeclared results should be skipped.protected PreparedStatementSetter
newArgPreparedStatementSetter
(Object[] args) Create a new arg-based PreparedStatementSetter using the args passed in.protected PreparedStatementSetter
newArgTypePreparedStatementSetter
(Object[] args, int[] argTypes) Create a new arg-type-based PreparedStatementSetter using the args and types passed in.Process the given ResultSet from a stored procedure.<T> T
query
(String sql, Object[] args, int[] argTypes, ResultSetExtractor<T> rse) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, reading the ResultSet with a ResultSetExtractor.void
query
(String sql, Object[] args, int[] argTypes, RowCallbackHandler rch) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, reading the ResultSet on a per-row basis with a RowCallbackHandler.<T> List<T>
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping each row to a result object via a RowMapper.<T> T
query
(String sql, Object[] args, ResultSetExtractor<T> rse) Deprecated.void
query
(String sql, Object[] args, RowCallbackHandler rch) Deprecated.<T> List<T>
Deprecated.<T> T
query
(String sql, PreparedStatementSetter pss, ResultSetExtractor<T> rse) Query using a prepared statement, reading the ResultSet with a ResultSetExtractor.void
query
(String sql, PreparedStatementSetter pss, RowCallbackHandler rch) Query given SQL to create a prepared statement from SQL and a PreparedStatementSetter implementation that knows how to bind values to the query, reading the ResultSet on a per-row basis with a RowCallbackHandler.<T> List<T>
query
(String sql, PreparedStatementSetter pss, RowMapper<T> rowMapper) Query given SQL to create a prepared statement from SQL and a PreparedStatementSetter implementation that knows how to bind values to the query, mapping each row to a result object via a RowMapper.<T> T
query
(String sql, ResultSetExtractor<T> rse) Execute a query given static SQL, reading the ResultSet with a ResultSetExtractor.<T> T
query
(String sql, ResultSetExtractor<T> rse, Object... args) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, reading the ResultSet with a ResultSetExtractor.void
query
(String sql, RowCallbackHandler rch) Execute a query given static SQL, reading the ResultSet on a per-row basis with a RowCallbackHandler.void
query
(String sql, RowCallbackHandler rch, Object... args) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, reading the ResultSet on a per-row basis with a RowCallbackHandler.<T> List<T>
Execute a query given static SQL, mapping each row to a result object via a RowMapper.<T> List<T>
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping each row to a result object via a RowMapper.<T> T
query
(PreparedStatementCreator psc, PreparedStatementSetter pss, ResultSetExtractor<T> rse) Query using a prepared statement, allowing for a PreparedStatementCreator and a PreparedStatementSetter.<T> T
query
(PreparedStatementCreator psc, ResultSetExtractor<T> rse) Query using a prepared statement, reading the ResultSet with a ResultSetExtractor.void
query
(PreparedStatementCreator psc, RowCallbackHandler rch) Query using a prepared statement, reading the ResultSet on a per-row basis with a RowCallbackHandler.<T> List<T>
query
(PreparedStatementCreator psc, RowMapper<T> rowMapper) Query using a prepared statement, mapping each row to a result object via a RowMapper.queryForList
(String sql) Execute a query for a result list, given static SQL.<T> List<T>
queryForList
(String sql, Class<T> elementType) Execute a query for a result list, given static SQL.<T> List<T>
queryForList
(String sql, Class<T> elementType, Object... args) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result list.queryForList
(String sql, Object... args) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result list.queryForList
(String sql, Object[] args, int[] argTypes) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result list.<T> List<T>
queryForList
(String sql, Object[] args, int[] argTypes, Class<T> elementType) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result list.<T> List<T>
queryForList
(String sql, Object[] args, Class<T> elementType) Deprecated.queryForMap
(String sql) Execute a query for a result map, given static SQL.queryForMap
(String sql, Object... args) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result map.queryForMap
(String sql, Object[] args, int[] argTypes) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result map.<T> T
queryForObject
(String sql, Class<T> requiredType) Execute a query for a result object, given static SQL.<T> T
queryForObject
(String sql, Class<T> requiredType, Object... args) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result object.<T> T
queryForObject
(String sql, Object[] args, int[] argTypes, Class<T> requiredType) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result object.<T> T
queryForObject
(String sql, Object[] args, int[] argTypes, RowMapper<T> rowMapper) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping a single result row to a result object via a RowMapper.<T> T
queryForObject
(String sql, Object[] args, Class<T> requiredType) Deprecated.<T> T
queryForObject
(String sql, Object[] args, RowMapper<T> rowMapper) Deprecated.<T> T
queryForObject
(String sql, RowMapper<T> rowMapper) Execute a query given static SQL, mapping a single result row to a result object via a RowMapper.<T> T
queryForObject
(String sql, RowMapper<T> rowMapper, Object... args) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping a single result row to a result object via a RowMapper.queryForRowSet
(String sql) Execute a query for an SqlRowSet, given static SQL.queryForRowSet
(String sql, Object... args) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting an SqlRowSet.queryForRowSet
(String sql, Object[] args, int[] argTypes) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting an SqlRowSet.<T> Stream<T>
queryForStream
(String sql, PreparedStatementSetter pss, RowMapper<T> rowMapper) Query given SQL to create a prepared statement from SQL and a PreparedStatementSetter implementation that knows how to bind values to the query, mapping each row to a result object via a RowMapper, and turning it into an iterable and closeable Stream.<T> Stream<T>
queryForStream
(String sql, RowMapper<T> rowMapper) Execute a query given static SQL, mapping each row to a result object via a RowMapper, and turning it into an iterable and closeable Stream.<T> Stream<T>
queryForStream
(String sql, RowMapper<T> rowMapper, Object... args) Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping each row to a result object via a RowMapper, and turning it into an iterable and closeable Stream.<T> Stream<T>
queryForStream
(PreparedStatementCreator psc, PreparedStatementSetter pss, RowMapper<T> rowMapper) Query using a prepared statement, allowing for a PreparedStatementCreator and a PreparedStatementSetter.<T> Stream<T>
queryForStream
(PreparedStatementCreator psc, RowMapper<T> rowMapper) Query using a prepared statement, mapping each row to a result object via a RowMapper, and turning it into an iterable and closeable Stream.void
setFetchSize
(int fetchSize) Set the fetch size for this JdbcTemplate.void
setIgnoreWarnings
(boolean ignoreWarnings) Set whether we want to ignore JDBC statement warnings (SQLWarning
).void
setMaxRows
(int maxRows) Set the maximum number of rows for this JdbcTemplate.void
setQueryTimeout
(int queryTimeout) Set the query timeout for statements that this JdbcTemplate executes.void
setResultsMapCaseInsensitive
(boolean resultsMapCaseInsensitive) Set whether execution of a CallableStatement will return the results in a Map that uses case-insensitive names for the parameters.void
setSkipResultsProcessing
(boolean skipResultsProcessing) Set whether results processing should be skipped.void
setSkipUndeclaredResults
(boolean skipUndeclaredResults) Set whether undeclared results should be skipped.protected DataAccessException
translateException
(String task, String sql, SQLException ex) Translate the givenSQLException
into a genericDataAccessException
.int
Issue a single SQL update operation (such as an insert, update or delete statement).int
Issue a single SQL update operation (such as an insert, update or delete statement) via a prepared statement, binding the given arguments.int
Issue a single SQL update operation (such as an insert, update or delete statement) via a prepared statement, binding the given arguments.int
update
(String sql, PreparedStatementSetter pss) Issue an update statement using a PreparedStatementSetter to set bind parameters, with given SQL.int
Issue a single SQL update operation (such as an insert, update or delete statement) using a PreparedStatementCreator to provide SQL and any required parameters.protected int
int
update
(PreparedStatementCreator psc, KeyHolder generatedKeyHolder) Issue an update statement using a PreparedStatementCreator to provide SQL and any required parameters.Methods inherited from class org.springframework.jdbc.support.JdbcAccessor
afterPropertiesSet, getDataSource, getExceptionTranslator, isLazyInit, obtainDataSource, setDatabaseProductName, setDataSource, setExceptionTranslator, setLazyInit
-
Constructor Details
-
JdbcTemplate
public JdbcTemplate()Construct a new JdbcTemplate for bean usage.Note: The DataSource has to be set before using the instance.
-
JdbcTemplate
Construct a new JdbcTemplate, given a DataSource to obtain connections from.Note: This will not trigger initialization of the exception translator.
- Parameters:
dataSource
- the JDBC DataSource to obtain connections from
-
JdbcTemplate
Construct a new JdbcTemplate, given a DataSource to obtain connections from.Note: Depending on the "lazyInit" flag, initialization of the exception translator will be triggered.
- Parameters:
dataSource
- the JDBC DataSource to obtain connections fromlazyInit
- whether to lazily initialize the SQLExceptionTranslator
-
-
Method Details
-
setIgnoreWarnings
public void setIgnoreWarnings(boolean ignoreWarnings) Set whether we want to ignore JDBC statement warnings (SQLWarning
).Default is
true
, swallowing and logging all warnings. Switch this flag tofalse
to make this JdbcTemplate throw aSQLWarningException
instead (or chain theSQLWarning
into the primarySQLException
, if any). -
isIgnoreWarnings
public boolean isIgnoreWarnings()Return whether we ignore SQLWarnings. -
setFetchSize
public void setFetchSize(int fetchSize) Set the fetch size for this JdbcTemplate. 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.Default is -1, indicating to use the JDBC driver's default configuration (i.e. to not pass a specific fetch size setting on to the driver).
Note: As of 4.3, negative values other than -1 will get passed on to the driver, since e.g. MySQL supports special behavior for
Integer.MIN_VALUE
.- See Also:
-
getFetchSize
public int getFetchSize()Return the fetch size specified for this JdbcTemplate. -
setMaxRows
public void setMaxRows(int maxRows) Set the maximum number of rows for this JdbcTemplate. 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 if we're never interested in the entire result in the first place (for example, when performing searches that might return a large number of matches).Default is -1, indicating to use the JDBC driver's default configuration (i.e. to not pass a specific max rows setting on to the driver).
Note: As of 4.3, negative values other than -1 will get passed on to the driver, in sync with
setFetchSize(int)
's support for special MySQL values.- See Also:
-
getMaxRows
public int getMaxRows()Return the maximum number of rows specified for this JdbcTemplate. -
setQueryTimeout
public void setQueryTimeout(int queryTimeout) Set the query timeout for statements that this JdbcTemplate executes.Default is -1, indicating to use the JDBC driver's default (i.e. to not pass a specific query timeout setting on the driver).
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.
- See Also:
-
getQueryTimeout
public int getQueryTimeout()Return the query timeout for statements that this JdbcTemplate executes. -
setSkipResultsProcessing
public void setSkipResultsProcessing(boolean skipResultsProcessing) Set whether results processing should be skipped. Can be used to optimize callable statement processing when we know that no results are being passed back - the processing of out parameter will still take place. This can be used to avoid a bug in some older Oracle JDBC drivers like 10.1.0.2. -
isSkipResultsProcessing
public boolean isSkipResultsProcessing()Return whether results processing should be skipped. -
setSkipUndeclaredResults
public void setSkipUndeclaredResults(boolean skipUndeclaredResults) Set whether undeclared results should be skipped. -
isSkipUndeclaredResults
public boolean isSkipUndeclaredResults()Return whether undeclared results should be skipped. -
setResultsMapCaseInsensitive
public void setResultsMapCaseInsensitive(boolean resultsMapCaseInsensitive) Set whether execution of a CallableStatement will return the results in a Map that uses case-insensitive names for the parameters. -
isResultsMapCaseInsensitive
public boolean isResultsMapCaseInsensitive()Return whether execution of a CallableStatement will return the results in a Map that uses case-insensitive names for the parameters. -
execute
Description copied from interface:JdbcOperations
Execute a JDBC data access operation, implemented as callback action working on a JDBC Connection. This allows for implementing arbitrary data access operations, within Spring's managed JDBC environment: that is, participating in Spring-managed transactions and converting JDBC SQLExceptions into Spring's DataAccessException hierarchy.The callback action can return a result object, for example a domain object or a collection of domain objects.
- Specified by:
execute
in interfaceJdbcOperations
- Parameters:
action
- a callback object that specifies the action- Returns:
- a result object returned by the action, or
null
if none - Throws:
DataAccessException
- if there is any problem
-
createConnectionProxy
Create a close-suppressing proxy for the given JDBC Connection. Called by theexecute
method.The proxy also prepares returned JDBC Statements, applying statement settings such as fetch size, max rows, and query timeout.
- Parameters:
con
- the JDBC Connection to create a proxy for- Returns:
- the Connection proxy
- See Also:
-
execute
Description copied from interface:JdbcOperations
Execute a JDBC data access operation, implemented as callback action working on a JDBC Statement. This allows for implementing arbitrary data access operations on a single Statement, within Spring's managed JDBC environment: that is, participating in Spring-managed transactions and converting JDBC SQLExceptions into Spring's DataAccessException hierarchy.The callback action can return a result object, for example a domain object or a collection of domain objects.
- Specified by:
execute
in interfaceJdbcOperations
- Parameters:
action
- a callback that specifies the action- Returns:
- a result object returned by the action, or
null
if none - Throws:
DataAccessException
- if there is any problem
-
execute
Description copied from interface:JdbcOperations
Issue a single SQL execute, typically a DDL statement.- Specified by:
execute
in interfaceJdbcOperations
- Parameters:
sql
- static SQL to execute- Throws:
DataAccessException
- if there is any problem
-
query
Description copied from interface:JdbcOperations
Execute a query given static SQL, reading the ResultSet with a ResultSetExtractor.Uses a JDBC Statement, not a PreparedStatement. If you want to execute a static query with a PreparedStatement, use the overloaded
query
method withnull
as argument array.- Specified by:
query
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executerse
- a callback that will extract all rows of results- Returns:
- an arbitrary result object, as returned by the ResultSetExtractor
- Throws:
DataAccessException
- if there is any problem executing the query- See Also:
-
query
Description copied from interface:JdbcOperations
Execute a query given static SQL, reading the ResultSet on a per-row basis with a RowCallbackHandler.Uses a JDBC Statement, not a PreparedStatement. If you want to execute a static query with a PreparedStatement, use the overloaded
query
method withnull
as argument array.- Specified by:
query
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executerch
- a callback that will extract results, one row at a time- Throws:
DataAccessException
- if there is any problem executing the query- See Also:
-
query
Description copied from interface:JdbcOperations
Execute a query given static SQL, mapping each row to a result object via a RowMapper.Uses a JDBC Statement, not a PreparedStatement. If you want to execute a static query with a PreparedStatement, use the overloaded
query
method withnull
as argument array.- Specified by:
query
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executerowMapper
- a callback that will map one object per row- Returns:
- the result List, containing mapped objects
- Throws:
DataAccessException
- if there is any problem executing the query- See Also:
-
queryForStream
Description copied from interface:JdbcOperations
Execute a query given static SQL, mapping each row to a result object via a RowMapper, and turning it into an iterable and closeable Stream.Uses a JDBC Statement, not a PreparedStatement. If you want to execute a static query with a PreparedStatement, use the overloaded
query
method withnull
as argument array.- Specified by:
queryForStream
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executerowMapper
- a callback that will map one object per row- Returns:
- the result Stream, containing mapped objects, needing to be closed once fully processed (e.g. through a try-with-resources clause)
- Throws:
DataAccessException
- if there is any problem executing the query- See Also:
-
queryForMap
Description copied from interface:JdbcOperations
Execute a query for a result map, given static SQL.Uses a JDBC Statement, not a PreparedStatement. If you want to execute a static query with a PreparedStatement, use the overloaded
JdbcOperations.queryForMap(String, Object...)
method withnull
as argument array.The query is expected to be a single row query; the result row will be mapped to a Map (one entry for each column, using the column name as the key).
- Specified by:
queryForMap
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to execute- Returns:
- the result Map (one entry per column, with column name as key)
- Throws:
IncorrectResultSizeDataAccessException
- if the query does not return exactly one rowDataAccessException
- if there is any problem executing the query- See Also:
-
queryForObject
@Nullable public <T> T queryForObject(String sql, RowMapper<T> rowMapper) throws DataAccessException Description copied from interface:JdbcOperations
Execute a query given static SQL, mapping a single result row to a result object via a RowMapper.Uses a JDBC Statement, not a PreparedStatement. If you want to execute a static query with a PreparedStatement, use the overloaded
JdbcOperations.queryForObject(String, RowMapper, Object...)
method withnull
as argument array.- Specified by:
queryForObject
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executerowMapper
- a callback that will map one object per row- Returns:
- the single mapped object (may be
null
if the givenRowMapper
returned null) - Throws:
IncorrectResultSizeDataAccessException
- if the query does not return exactly one rowDataAccessException
- if there is any problem executing the query- See Also:
-
queryForObject
Description copied from interface:JdbcOperations
Execute a query for a result object, given static SQL.Uses a JDBC Statement, not a PreparedStatement. If you want to execute a static query with a PreparedStatement, use the overloaded
JdbcOperations.queryForObject(String, Class, Object...)
method withnull
as argument array.This method is useful for running static SQL with a known outcome. The query is expected to be a single row/single column query; the returned result will be directly mapped to the corresponding object type.
- Specified by:
queryForObject
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executerequiredType
- the type that the result object is expected to match- Returns:
- the result object of the required type, or
null
in case of SQL NULL - Throws:
IncorrectResultSizeDataAccessException
- if the query does not return exactly one rowIncorrectResultSetColumnCountException
- if the query does not return a row containing a single columnDataAccessException
- if there is any problem executing the query- See Also:
-
queryForList
Description copied from interface:JdbcOperations
Execute a query for a result list, given static SQL.Uses a JDBC Statement, not a PreparedStatement. If you want to execute a static query with a PreparedStatement, use the overloaded
queryForList
method withnull
as argument array.The results will be mapped to a List (one entry for each row) of result objects, each of them matching the specified element type.
- Specified by:
queryForList
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeelementType
- the required type of element in the result list (for example,Integer.class
)- Returns:
- a List of objects that match the specified element type
- Throws:
DataAccessException
- if there is any problem executing the query- See Also:
-
queryForList
Description copied from interface:JdbcOperations
Execute a query for a result list, given static SQL.Uses a JDBC Statement, not a PreparedStatement. If you want to execute a static query with a PreparedStatement, use the overloaded
queryForList
method withnull
as argument array.The results will be mapped to a List (one entry for each row) of Maps (one entry for each column using the column name as the key). Each element in the list will be of the form returned by this interface's
queryForMap
methods.- Specified by:
queryForList
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to execute- Returns:
- a List that contains a Map per row
- Throws:
DataAccessException
- if there is any problem executing the query- See Also:
-
queryForRowSet
Description copied from interface:JdbcOperations
Execute a query for an SqlRowSet, given static SQL.Uses a JDBC Statement, not a PreparedStatement. If you want to execute a static query with a PreparedStatement, use the overloaded
queryForRowSet
method withnull
as argument array.The results will be mapped to an SqlRowSet which holds the data in a disconnected fashion. This wrapper will translate any SQLExceptions thrown.
Note that, for the default implementation, JDBC RowSet support needs to be available at runtime: by default, Sun's
com.sun.rowset.CachedRowSetImpl
class is used, which is part of JDK 1.5+ and also available separately as part of Sun's JDBC RowSet Implementations download (rowset.jar).- Specified by:
queryForRowSet
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to execute- Returns:
- an SqlRowSet representation (possibly a wrapper around a
javax.sql.rowset.CachedRowSet
) - Throws:
DataAccessException
- if there is any problem executing the query- See Also:
-
update
Description copied from interface:JdbcOperations
Issue a single SQL update operation (such as an insert, update or delete statement).- Specified by:
update
in interfaceJdbcOperations
- Parameters:
sql
- static SQL to execute- Returns:
- the number of rows affected
- Throws:
DataAccessException
- if there is any problem.
-
batchUpdate
Description copied from interface:JdbcOperations
Issue multiple SQL updates on a single JDBC Statement using batching.Will fall back to separate updates on a single Statement if the JDBC driver does not support batch updates.
- Specified by:
batchUpdate
in interfaceJdbcOperations
- Parameters:
sql
- defining an array of SQL statements that will be executed.- Returns:
- an array of the number of rows affected by each statement
- Throws:
DataAccessException
- if there is any problem executing the batch
-
execute
@Nullable public <T> T execute(PreparedStatementCreator psc, PreparedStatementCallback<T> action) throws DataAccessException Description copied from interface:JdbcOperations
Execute a JDBC data access operation, implemented as callback action working on a JDBC PreparedStatement. This allows for implementing arbitrary data access operations on a single Statement, within Spring's managed JDBC environment: that is, participating in Spring-managed transactions and converting JDBC SQLExceptions into Spring's DataAccessException hierarchy.The callback action can return a result object, for example a domain object or a collection of domain objects.
- Specified by:
execute
in interfaceJdbcOperations
- Parameters:
psc
- a callback that creates a PreparedStatement given a Connectionaction
- a callback that specifies the action- Returns:
- a result object returned by the action, or
null
if none - Throws:
DataAccessException
- if there is any problem
-
execute
@Nullable public <T> T execute(String sql, PreparedStatementCallback<T> action) throws DataAccessException Description copied from interface:JdbcOperations
Execute a JDBC data access operation, implemented as callback action working on a JDBC PreparedStatement. This allows for implementing arbitrary data access operations on a single Statement, within Spring's managed JDBC environment: that is, participating in Spring-managed transactions and converting JDBC SQLExceptions into Spring's DataAccessException hierarchy.The callback action can return a result object, for example a domain object or a collection of domain objects.
- Specified by:
execute
in interfaceJdbcOperations
- Parameters:
sql
- the SQL to executeaction
- a callback that specifies the action- Returns:
- a result object returned by the action, or
null
if none - Throws:
DataAccessException
- if there is any problem
-
query
@Nullable public <T> T query(PreparedStatementCreator psc, @Nullable PreparedStatementSetter pss, ResultSetExtractor<T> rse) throws DataAccessException Query using a prepared statement, allowing for a PreparedStatementCreator and a PreparedStatementSetter. Most other query methods use this method, but application code will always work with either a creator or a setter.- Parameters:
psc
- a callback that creates a PreparedStatement given a Connectionpss
- a callback that knows how to set values on the prepared statement. If this isnull
, the SQL will be assumed to contain no bind parameters.rse
- a callback that will extract results- Returns:
- an arbitrary result object, as returned by the ResultSetExtractor
- Throws:
DataAccessException
- if there is any problem
-
query
@Nullable public <T> T query(PreparedStatementCreator psc, ResultSetExtractor<T> rse) throws DataAccessException Description copied from interface:JdbcOperations
Query using a prepared statement, reading the ResultSet with a ResultSetExtractor.A PreparedStatementCreator can either be implemented directly or configured through a PreparedStatementCreatorFactory.
- Specified by:
query
in interfaceJdbcOperations
- Parameters:
psc
- a callback that creates a PreparedStatement given a Connectionrse
- a callback that will extract results- Returns:
- an arbitrary result object, as returned by the ResultSetExtractor
- Throws:
DataAccessException
- if there is any problem- See Also:
-
query
@Nullable public <T> T query(String sql, @Nullable PreparedStatementSetter pss, ResultSetExtractor<T> rse) throws DataAccessException Description copied from interface:JdbcOperations
Query using a prepared statement, reading the ResultSet with a ResultSetExtractor.- Specified by:
query
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executepss
- a callback that knows how to set values on the prepared statement. If this isnull
, the SQL will be assumed to contain no bind parameters. Even if there are no bind parameters, this callback may be used to set the fetch size and other performance options.rse
- a callback that will extract results- Returns:
- an arbitrary result object, as returned by the ResultSetExtractor
- Throws:
DataAccessException
- if there is any problem
-
query
@Nullable public <T> T query(String sql, Object[] args, int[] argTypes, ResultSetExtractor<T> rse) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, reading the ResultSet with a ResultSetExtractor.- Specified by:
query
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the queryargTypes
- the SQL types of the arguments (constants fromjava.sql.Types
)rse
- a callback that will extract results- Returns:
- an arbitrary result object, as returned by the ResultSetExtractor
- Throws:
DataAccessException
- if the query fails- See Also:
-
query
@Deprecated @Nullable public <T> T query(String sql, @Nullable Object[] args, ResultSetExtractor<T> rse) throws DataAccessException Deprecated.Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, reading the ResultSet with a ResultSetExtractor.- Specified by:
query
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scalerse
- a callback that will extract results- Returns:
- an arbitrary result object, as returned by the ResultSetExtractor
- Throws:
DataAccessException
- if the query fails
-
query
@Nullable public <T> T query(String sql, ResultSetExtractor<T> rse, @Nullable Object... args) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, reading the ResultSet with a ResultSetExtractor.- Specified by:
query
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executerse
- a callback that will extract resultsargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scale- Returns:
- an arbitrary result object, as returned by the ResultSetExtractor
- Throws:
DataAccessException
- if the query fails
-
query
Description copied from interface:JdbcOperations
Query using a prepared statement, reading the ResultSet on a per-row basis with a RowCallbackHandler.A PreparedStatementCreator can either be implemented directly or configured through a PreparedStatementCreatorFactory.
- Specified by:
query
in interfaceJdbcOperations
- Parameters:
psc
- a callback that creates a PreparedStatement given a Connectionrch
- a callback that will extract results, one row at a time- Throws:
DataAccessException
- if there is any problem- See Also:
-
query
public void query(String sql, @Nullable PreparedStatementSetter pss, RowCallbackHandler rch) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a PreparedStatementSetter implementation that knows how to bind values to the query, reading the ResultSet on a per-row basis with a RowCallbackHandler.- Specified by:
query
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executepss
- a callback that knows how to set values on the prepared statement. If this isnull
, the SQL will be assumed to contain no bind parameters. Even if there are no bind parameters, this callback may be used to set the fetch size and other performance options.rch
- a callback that will extract results, one row at a time- Throws:
DataAccessException
- if the query fails
-
query
public void query(String sql, Object[] args, int[] argTypes, RowCallbackHandler rch) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, reading the ResultSet on a per-row basis with a RowCallbackHandler.- Specified by:
query
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the queryargTypes
- the SQL types of the arguments (constants fromjava.sql.Types
)rch
- a callback that will extract results, one row at a time- Throws:
DataAccessException
- if the query fails- See Also:
-
query
@Deprecated public void query(String sql, @Nullable Object[] args, RowCallbackHandler rch) throws DataAccessException Deprecated.Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, reading the ResultSet on a per-row basis with a RowCallbackHandler.- Specified by:
query
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scalerch
- a callback that will extract results, one row at a time- Throws:
DataAccessException
- if the query fails
-
query
public void query(String sql, RowCallbackHandler rch, @Nullable Object... args) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, reading the ResultSet on a per-row basis with a RowCallbackHandler.- Specified by:
query
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executerch
- a callback that will extract results, one row at a timeargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scale- Throws:
DataAccessException
- if the query fails
-
query
public <T> List<T> query(PreparedStatementCreator psc, RowMapper<T> rowMapper) throws DataAccessException Description copied from interface:JdbcOperations
Query using a prepared statement, mapping each row to a result object via a RowMapper.A PreparedStatementCreator can either be implemented directly or configured through a PreparedStatementCreatorFactory.
- Specified by:
query
in interfaceJdbcOperations
- Parameters:
psc
- a callback that creates a PreparedStatement given a ConnectionrowMapper
- a callback that will map one object per row- Returns:
- the result List, containing mapped objects
- Throws:
DataAccessException
- if there is any problem- See Also:
-
query
public <T> List<T> query(String sql, @Nullable PreparedStatementSetter pss, RowMapper<T> rowMapper) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a PreparedStatementSetter implementation that knows how to bind values to the query, mapping each row to a result object via a RowMapper.- Specified by:
query
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executepss
- a callback that knows how to set values on the prepared statement. If this isnull
, the SQL will be assumed to contain no bind parameters. Even if there are no bind parameters, this callback may be used to set the fetch size and other performance options.rowMapper
- a callback that will map one object per row- Returns:
- the result List, containing mapped objects
- Throws:
DataAccessException
- if the query fails
-
query
public <T> List<T> query(String sql, Object[] args, int[] argTypes, RowMapper<T> rowMapper) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping each row to a result object via a RowMapper.- Specified by:
query
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the queryargTypes
- the SQL types of the arguments (constants fromjava.sql.Types
)rowMapper
- a callback that will map one object per row- Returns:
- the result List, containing mapped objects
- Throws:
DataAccessException
- if the query fails- See Also:
-
query
@Deprecated public <T> List<T> query(String sql, @Nullable Object[] args, RowMapper<T> rowMapper) throws DataAccessException Deprecated.Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping each row to a result object via a RowMapper.- Specified by:
query
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scalerowMapper
- a callback that will map one object per row- Returns:
- the result List, containing mapped objects
- Throws:
DataAccessException
- if the query fails
-
query
public <T> List<T> query(String sql, RowMapper<T> rowMapper, @Nullable Object... args) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping each row to a result object via a RowMapper.- Specified by:
query
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executerowMapper
- a callback that will map one object per rowargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scale- Returns:
- the result List, containing mapped objects
- Throws:
DataAccessException
- if the query fails
-
queryForStream
public <T> Stream<T> queryForStream(PreparedStatementCreator psc, @Nullable PreparedStatementSetter pss, RowMapper<T> rowMapper) throws DataAccessException Query using a prepared statement, allowing for a PreparedStatementCreator and a PreparedStatementSetter. Most other query methods use this method, but application code will always work with either a creator or a setter.- Parameters:
psc
- a callback that creates a PreparedStatement given a Connectionpss
- a callback that knows how to set values on the prepared statement. If this isnull
, the SQL will be assumed to contain no bind parameters.rowMapper
- a callback that will map one object per row- Returns:
- the result Stream, containing mapped objects, needing to be closed once fully processed (e.g. through a try-with-resources clause)
- Throws:
DataAccessException
- if the query fails- Since:
- 5.3
-
queryForStream
public <T> Stream<T> queryForStream(PreparedStatementCreator psc, RowMapper<T> rowMapper) throws DataAccessException Description copied from interface:JdbcOperations
Query using a prepared statement, mapping each row to a result object via a RowMapper, and turning it into an iterable and closeable Stream.A PreparedStatementCreator can either be implemented directly or configured through a PreparedStatementCreatorFactory.
- Specified by:
queryForStream
in interfaceJdbcOperations
- Parameters:
psc
- a callback that creates a PreparedStatement given a ConnectionrowMapper
- a callback that will map one object per row- Returns:
- the result Stream, containing mapped objects, needing to be closed once fully processed (e.g. through a try-with-resources clause)
- Throws:
DataAccessException
- if there is any problem- See Also:
-
queryForStream
public <T> Stream<T> queryForStream(String sql, @Nullable PreparedStatementSetter pss, RowMapper<T> rowMapper) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a PreparedStatementSetter implementation that knows how to bind values to the query, mapping each row to a result object via a RowMapper, and turning it into an iterable and closeable Stream.- Specified by:
queryForStream
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executepss
- a callback that knows how to set values on the prepared statement. If this isnull
, the SQL will be assumed to contain no bind parameters. Even if there are no bind parameters, this callback may be used to set the fetch size and other performance options.rowMapper
- a callback that will map one object per row- Returns:
- the result Stream, containing mapped objects, needing to be closed once fully processed (e.g. through a try-with-resources clause)
- Throws:
DataAccessException
- if the query fails
-
queryForStream
public <T> Stream<T> queryForStream(String sql, RowMapper<T> rowMapper, @Nullable Object... args) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping each row to a result object via a RowMapper, and turning it into an iterable and closeable Stream.- Specified by:
queryForStream
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executerowMapper
- a callback that will map one object per rowargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scale- Returns:
- the result Stream, containing mapped objects, needing to be closed once fully processed (e.g. through a try-with-resources clause)
- Throws:
DataAccessException
- if the query fails
-
queryForObject
@Nullable public <T> T queryForObject(String sql, Object[] args, int[] argTypes, RowMapper<T> rowMapper) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping a single result row to a result object via a RowMapper.- Specified by:
queryForObject
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type)argTypes
- the SQL types of the arguments (constants fromjava.sql.Types
)rowMapper
- a callback that will map one object per row- Returns:
- the single mapped object (may be
null
if the givenRowMapper
returned null) - Throws:
IncorrectResultSizeDataAccessException
- if the query does not return exactly one rowDataAccessException
- if the query fails
-
queryForObject
@Deprecated @Nullable public <T> T queryForObject(String sql, @Nullable Object[] args, RowMapper<T> rowMapper) throws DataAccessException Deprecated.Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping a single result row to a result object via a RowMapper.- Specified by:
queryForObject
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scalerowMapper
- a callback that will map one object per row- Returns:
- the single mapped object (may be
null
if the givenRowMapper
returned null) - Throws:
IncorrectResultSizeDataAccessException
- if the query does not return exactly one rowDataAccessException
- if the query fails
-
queryForObject
@Nullable public <T> T queryForObject(String sql, RowMapper<T> rowMapper, @Nullable Object... args) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, mapping a single result row to a result object via a RowMapper.- Specified by:
queryForObject
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executerowMapper
- a callback that will map one object per rowargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scale- Returns:
- the single mapped object (may be
null
if the givenRowMapper
returned null) - Throws:
IncorrectResultSizeDataAccessException
- if the query does not return exactly one rowDataAccessException
- if the query fails
-
queryForObject
@Nullable public <T> T queryForObject(String sql, Object[] args, int[] argTypes, Class<T> requiredType) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result object.The query is expected to be a single row/single column query; the returned result will be directly mapped to the corresponding object type.
- Specified by:
queryForObject
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the queryargTypes
- the SQL types of the arguments (constants fromjava.sql.Types
)requiredType
- the type that the result object is expected to match- Returns:
- the result object of the required type, or
null
in case of SQL NULL - Throws:
IncorrectResultSizeDataAccessException
- if the query does not return exactly one rowIncorrectResultSetColumnCountException
- if the query does not return a row containing a single columnDataAccessException
- if the query fails- See Also:
-
queryForObject
@Deprecated public <T> T queryForObject(String sql, @Nullable Object[] args, Class<T> requiredType) throws DataAccessException Deprecated.Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result object.The query is expected to be a single row/single column query; the returned result will be directly mapped to the corresponding object type.
- Specified by:
queryForObject
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scalerequiredType
- the type that the result object is expected to match- Returns:
- the result object of the required type, or
null
in case of SQL NULL - Throws:
IncorrectResultSizeDataAccessException
- if the query does not return exactly one rowIncorrectResultSetColumnCountException
- if the query does not return a row containing a single columnDataAccessException
- if the query fails- See Also:
-
queryForObject
public <T> T queryForObject(String sql, Class<T> requiredType, @Nullable Object... args) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result object.The query is expected to be a single row/single column query; the returned result will be directly mapped to the corresponding object type.
- Specified by:
queryForObject
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executerequiredType
- the type that the result object is expected to matchargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scale- Returns:
- the result object of the required type, or
null
in case of SQL NULL - Throws:
IncorrectResultSizeDataAccessException
- if the query does not return exactly one rowIncorrectResultSetColumnCountException
- if the query does not return a row containing a single columnDataAccessException
- if the query fails- See Also:
-
queryForMap
public Map<String,Object> queryForMap(String sql, Object[] args, int[] argTypes) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result map.The query is expected to be a single row query; the result row will be mapped to a Map (one entry for each column, using the column name as the key).
- Specified by:
queryForMap
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the queryargTypes
- the SQL types of the arguments (constants fromjava.sql.Types
)- Returns:
- the result Map (one entry per column, with column name as key)
- Throws:
IncorrectResultSizeDataAccessException
- if the query does not return exactly one rowDataAccessException
- if the query fails- See Also:
-
queryForMap
public Map<String,Object> queryForMap(String sql, @Nullable Object... args) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result map.The
queryForMap
methods defined by this interface are appropriate when you don't have a domain model. Otherwise, consider using one of thequeryForObject
methods.The query is expected to be a single row query; the result row will be mapped to a Map (one entry for each column, using the column name as the key).
- Specified by:
queryForMap
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scale- Returns:
- the result Map (one entry for each column, using the column name as the key)
- Throws:
IncorrectResultSizeDataAccessException
- if the query does not return exactly one rowDataAccessException
- if the query fails- See Also:
-
queryForList
public <T> List<T> queryForList(String sql, Object[] args, int[] argTypes, Class<T> elementType) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result list.The results will be mapped to a List (one entry for each row) of result objects, each of them matching the specified element type.
- Specified by:
queryForList
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the queryargTypes
- the SQL types of the arguments (constants fromjava.sql.Types
)elementType
- the required type of element in the result list (for example,Integer.class
)- Returns:
- a List of objects that match the specified element type
- Throws:
DataAccessException
- if the query fails- See Also:
-
queryForList
@Deprecated public <T> List<T> queryForList(String sql, @Nullable Object[] args, Class<T> elementType) throws DataAccessException Deprecated.Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result list.The results will be mapped to a List (one entry for each row) of result objects, each of them matching the specified element type.
- Specified by:
queryForList
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scaleelementType
- the required type of element in the result list (for example,Integer.class
)- Returns:
- a List of objects that match the specified element type
- Throws:
DataAccessException
- if the query fails- See Also:
-
queryForList
public <T> List<T> queryForList(String sql, Class<T> elementType, @Nullable Object... args) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result list.The results will be mapped to a List (one entry for each row) of result objects, each of them matching the specified element type.
- Specified by:
queryForList
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeelementType
- the required type of element in the result list (for example,Integer.class
)args
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scale- Returns:
- a List of objects that match the specified element type
- Throws:
DataAccessException
- if the query fails- See Also:
-
queryForList
public List<Map<String,Object>> queryForList(String sql, Object[] args, int[] argTypes) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result list.The results will be mapped to a List (one entry for each row) of Maps (one entry for each column, using the column name as the key). Each element in the list will be of the form returned by this interface's
queryForMap
methods.- Specified by:
queryForList
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the queryargTypes
- the SQL types of the arguments (constants fromjava.sql.Types
)- Returns:
- a List that contains a Map per row
- Throws:
DataAccessException
- if the query fails- See Also:
-
queryForList
public List<Map<String,Object>> queryForList(String sql, @Nullable Object... args) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result list.The results will be mapped to a List (one entry for each row) of Maps (one entry for each column, using the column name as the key). Each element in the list will be of the form returned by this interface's
queryForMap
methods.- Specified by:
queryForList
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scale- Returns:
- a List that contains a Map per row
- Throws:
DataAccessException
- if the query fails- See Also:
-
queryForRowSet
public SqlRowSet queryForRowSet(String sql, Object[] args, int[] argTypes) throws DataAccessException Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting an SqlRowSet.The results will be mapped to an SqlRowSet which holds the data in a disconnected fashion. This wrapper will translate any SQLExceptions thrown.
Note that, for the default implementation, JDBC RowSet support needs to be available at runtime: by default, Sun's
com.sun.rowset.CachedRowSetImpl
class is used, which is part of JDK 1.5+ and also available separately as part of Sun's JDBC RowSet Implementations download (rowset.jar).- Specified by:
queryForRowSet
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the queryargTypes
- the SQL types of the arguments (constants fromjava.sql.Types
)- Returns:
- an SqlRowSet representation (possibly a wrapper around a
javax.sql.rowset.CachedRowSet
) - Throws:
DataAccessException
- if there is any problem executing the query- See Also:
-
queryForRowSet
Description copied from interface:JdbcOperations
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting an SqlRowSet.The results will be mapped to an SqlRowSet which holds the data in a disconnected fashion. This wrapper will translate any SQLExceptions thrown.
Note that, for the default implementation, JDBC RowSet support needs to be available at runtime: by default, Sun's
com.sun.rowset.CachedRowSetImpl
class is used, which is part of JDK 1.5+ and also available separately as part of Sun's JDBC RowSet Implementations download (rowset.jar).- Specified by:
queryForRowSet
in interfaceJdbcOperations
- Parameters:
sql
- the SQL query to executeargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scale- Returns:
- an SqlRowSet representation (possibly a wrapper around a
javax.sql.rowset.CachedRowSet
) - Throws:
DataAccessException
- if there is any problem executing the query- See Also:
-
update
protected int update(PreparedStatementCreator psc, @Nullable PreparedStatementSetter pss) throws DataAccessException - Throws:
DataAccessException
-
update
Description copied from interface:JdbcOperations
Issue a single SQL update operation (such as an insert, update or delete statement) using a PreparedStatementCreator to provide SQL and any required parameters.A PreparedStatementCreator can either be implemented directly or configured through a PreparedStatementCreatorFactory.
- Specified by:
update
in interfaceJdbcOperations
- Parameters:
psc
- a callback that provides SQL and any necessary parameters- Returns:
- the number of rows affected
- Throws:
DataAccessException
- if there is any problem issuing the update- See Also:
-
update
public int update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder) throws DataAccessException Description copied from interface:JdbcOperations
Issue an update statement using a PreparedStatementCreator to provide SQL and any required parameters. Generated keys will be put into the given KeyHolder.Note that the given PreparedStatementCreator has to create a statement with activated extraction of generated keys (a JDBC 3.0 feature). This can either be done directly or through using a PreparedStatementCreatorFactory.
This method requires support for generated keys in the JDBC driver.
- Specified by:
update
in interfaceJdbcOperations
- Parameters:
psc
- a callback that provides SQL and any necessary parametersgeneratedKeyHolder
- a KeyHolder that will hold the generated keys- Returns:
- the number of rows affected
- Throws:
DataAccessException
- if there is any problem issuing the update- See Also:
-
update
Description copied from interface:JdbcOperations
Issue an update statement using a PreparedStatementSetter to set bind parameters, with given SQL. Simpler than using a PreparedStatementCreator as this method will create the PreparedStatement: The PreparedStatementSetter just needs to set parameters.- Specified by:
update
in interfaceJdbcOperations
- Parameters:
sql
- the SQL containing bind parameterspss
- helper that sets bind parameters. If this isnull
we run an update with static SQL.- Returns:
- the number of rows affected
- Throws:
DataAccessException
- if there is any problem issuing the update
-
update
Description copied from interface:JdbcOperations
Issue a single SQL update operation (such as an insert, update or delete statement) via a prepared statement, binding the given arguments.- Specified by:
update
in interfaceJdbcOperations
- Parameters:
sql
- the SQL containing bind parametersargs
- arguments to bind to the queryargTypes
- the SQL types of the arguments (constants fromjava.sql.Types
)- Returns:
- the number of rows affected
- Throws:
DataAccessException
- if there is any problem issuing the update- See Also:
-
update
Description copied from interface:JdbcOperations
Issue a single SQL update operation (such as an insert, update or delete statement) via a prepared statement, binding the given arguments.- Specified by:
update
in interfaceJdbcOperations
- Parameters:
sql
- the SQL containing bind parametersargs
- arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also containSqlParameterValue
objects which indicate not only the argument value but also the SQL type and optionally the scale- Returns:
- the number of rows affected
- Throws:
DataAccessException
- if there is any problem issuing the update
-
batchUpdate
public int[] batchUpdate(PreparedStatementCreator psc, BatchPreparedStatementSetter pss, KeyHolder generatedKeyHolder) throws DataAccessException Description copied from interface:JdbcOperations
Issue multiple update statements on a single PreparedStatement, using batch updates and a BatchPreparedStatementSetter to set values. Generated keys will be put into the given KeyHolder.Note that the given PreparedStatementCreator has to create a statement with activated extraction of generated keys (a JDBC 3.0 feature). This can either be done directly or through using a PreparedStatementCreatorFactory.
This method requires support for generated keys in the JDBC driver. It will fall back to separate updates on a single PreparedStatement if the JDBC driver does not support batch updates.
- Specified by:
batchUpdate
in interfaceJdbcOperations
- Parameters:
psc
- a callback that creates a PreparedStatement given a Connectionpss
- object to set parameters on the PreparedStatement created by this methodgeneratedKeyHolder
- a KeyHolder that will hold the generated keys- Returns:
- an array of the number of rows affected by each statement
(may also contain special JDBC-defined negative values for affected rows such as
Statement.SUCCESS_NO_INFO
/Statement.EXECUTE_FAILED
) - Throws:
DataAccessException
- if there is any problem issuing the update- See Also:
-
batchUpdate
Description copied from interface:JdbcOperations
Issue multiple update statements on a single PreparedStatement, using batch updates and a BatchPreparedStatementSetter to set values.Will fall back to separate updates on a single PreparedStatement if the JDBC driver does not support batch updates.
- Specified by:
batchUpdate
in interfaceJdbcOperations
- Parameters:
sql
- defining PreparedStatement that will be reused. All statements in the batch will use the same SQL.pss
- object to set parameters on the PreparedStatement created by this method- Returns:
- an array of the number of rows affected by each statement
(may also contain special JDBC-defined negative values for affected rows such as
Statement.SUCCESS_NO_INFO
/Statement.EXECUTE_FAILED
) - Throws:
DataAccessException
- if there is any problem issuing the update
-
batchUpdate
Description copied from interface:JdbcOperations
Execute a batch using the supplied SQL statement with the batch of supplied arguments.- Specified by:
batchUpdate
in interfaceJdbcOperations
- Parameters:
sql
- the SQL statement to executebatchArgs
- the List of Object arrays containing the batch of arguments for the query- Returns:
- an array containing the numbers of rows affected by each update in the batch
(may also contain special JDBC-defined negative values for affected rows such as
Statement.SUCCESS_NO_INFO
/Statement.EXECUTE_FAILED
) - Throws:
DataAccessException
- if there is any problem issuing the update
-
batchUpdate
public int[] batchUpdate(String sql, List<Object[]> batchArgs, int[] argTypes) throws DataAccessException Description copied from interface:JdbcOperations
Execute a batch using the supplied SQL statement with the batch of supplied arguments.- Specified by:
batchUpdate
in interfaceJdbcOperations
- Parameters:
sql
- the SQL statement to execute.batchArgs
- the List of Object arrays containing the batch of arguments for the queryargTypes
- the SQL types of the arguments (constants fromjava.sql.Types
)- Returns:
- an array containing the numbers of rows affected by each update in the batch
(may also contain special JDBC-defined negative values for affected rows such as
Statement.SUCCESS_NO_INFO
/Statement.EXECUTE_FAILED
) - Throws:
DataAccessException
- if there is any problem issuing the update
-
batchUpdate
public <T> int[][] batchUpdate(String sql, Collection<T> batchArgs, int batchSize, ParameterizedPreparedStatementSetter<T> pss) throws DataAccessException Description copied from interface:JdbcOperations
Execute multiple batches using the supplied SQL statement with the collect of supplied arguments. The arguments' values will be set using the ParameterizedPreparedStatementSetter. Each batch should be of size indicated in 'batchSize'.- Specified by:
batchUpdate
in interfaceJdbcOperations
- Parameters:
sql
- the SQL statement to execute.batchArgs
- the List of Object arrays containing the batch of arguments for the querybatchSize
- batch sizepss
- the ParameterizedPreparedStatementSetter to use- Returns:
- an array containing for each batch another array containing the numbers of
rows affected by each update in the batch
(may also contain special JDBC-defined negative values for affected rows such as
Statement.SUCCESS_NO_INFO
/Statement.EXECUTE_FAILED
) - Throws:
DataAccessException
- if there is any problem issuing the update
-
execute
@Nullable public <T> T execute(CallableStatementCreator csc, CallableStatementCallback<T> action) throws DataAccessException Description copied from interface:JdbcOperations
Execute a JDBC data access operation, implemented as callback action working on a JDBC CallableStatement. This allows for implementing arbitrary data access operations on a single Statement, within Spring's managed JDBC environment: that is, participating in Spring-managed transactions and converting JDBC SQLExceptions into Spring's DataAccessException hierarchy.The callback action can return a result object, for example a domain object or a collection of domain objects.
- Specified by:
execute
in interfaceJdbcOperations
- Parameters:
csc
- a callback that creates a CallableStatement given a Connectionaction
- a callback that specifies the action- Returns:
- a result object returned by the action, or
null
if none - Throws:
DataAccessException
- if there is any problem
-
execute
@Nullable public <T> T execute(String callString, CallableStatementCallback<T> action) throws DataAccessException Description copied from interface:JdbcOperations
Execute a JDBC data access operation, implemented as callback action working on a JDBC CallableStatement. This allows for implementing arbitrary data access operations on a single Statement, within Spring's managed JDBC environment: that is, participating in Spring-managed transactions and converting JDBC SQLExceptions into Spring's DataAccessException hierarchy.The callback action can return a result object, for example a domain object or a collection of domain objects.
- Specified by:
execute
in interfaceJdbcOperations
- Parameters:
callString
- the SQL call string to executeaction
- a callback that specifies the action- Returns:
- a result object returned by the action, or
null
if none - Throws:
DataAccessException
- if there is any problem
-
call
public Map<String,Object> call(CallableStatementCreator csc, List<SqlParameter> declaredParameters) throws DataAccessException Description copied from interface:JdbcOperations
Execute an SQL call using a CallableStatementCreator to provide SQL and any required parameters.- Specified by:
call
in interfaceJdbcOperations
- Parameters:
csc
- a callback that provides SQL and any necessary parametersdeclaredParameters
- list of declared SqlParameter objects- Returns:
- a Map of extracted out parameters
- Throws:
DataAccessException
- if there is any problem issuing the update
-
extractReturnedResults
protected Map<String,Object> extractReturnedResults(CallableStatement cs, @Nullable List<SqlParameter> updateCountParameters, @Nullable List<SqlParameter> resultSetParameters, int updateCount) throws SQLException Extract returned ResultSets from the completed stored procedure.- Parameters:
cs
- a JDBC wrapper for the stored procedureupdateCountParameters
- the parameter list of declared update count parameters for the stored procedureresultSetParameters
- the parameter list of declared resultSet parameters for the stored procedure- Returns:
- a Map that contains returned results
- Throws:
SQLException
-
extractOutputParameters
protected Map<String,Object> extractOutputParameters(CallableStatement cs, List<SqlParameter> parameters) throws SQLException Extract output parameters from the completed stored procedure.- Parameters:
cs
- the JDBC wrapper for the stored procedureparameters
- parameter list for the stored procedure- Returns:
- a Map that contains returned results
- Throws:
SQLException
-
processResultSet
protected Map<String,Object> processResultSet(@Nullable ResultSet rs, ResultSetSupportingSqlParameter param) throws SQLException Process the given ResultSet from a stored procedure.- Parameters:
rs
- the ResultSet to processparam
- the corresponding stored procedure parameter- Returns:
- a Map that contains returned results
- Throws:
SQLException
-
getColumnMapRowMapper
Create a new RowMapper for reading columns as key-value pairs.- Returns:
- the RowMapper to use
- See Also:
-
getSingleColumnRowMapper
Create a new RowMapper for reading result objects from a single column.- Parameters:
requiredType
- the type that each result object is expected to match- Returns:
- the RowMapper to use
- See Also:
-
createResultsMap
Create a Map instance to be used as the results map.If
resultsMapCaseInsensitive
has been set to true, aLinkedCaseInsensitiveMap
will be created; otherwise, aLinkedHashMap
will be created.- Returns:
- the results Map instance
- See Also:
-
applyStatementSettings
Prepare the given JDBC Statement (or PreparedStatement or CallableStatement), applying statement settings such as fetch size, max rows, and query timeout.- Parameters:
stmt
- the JDBC Statement to prepare- Throws:
SQLException
- if thrown by JDBC API- See Also:
-
newArgPreparedStatementSetter
Create a new arg-based PreparedStatementSetter using the args passed in.By default, we'll create an
ArgumentPreparedStatementSetter
. This method allows for the creation to be overridden by subclasses.- Parameters:
args
- object array with arguments- Returns:
- the new PreparedStatementSetter to use
-
newArgTypePreparedStatementSetter
Create a new arg-type-based PreparedStatementSetter using the args and types passed in.By default, we'll create an
ArgumentTypePreparedStatementSetter
. This method allows for the creation to be overridden by subclasses.- Parameters:
args
- object array with argumentsargTypes
- int array of SQLTypes for the associated arguments- Returns:
- the new PreparedStatementSetter to use
-
handleWarnings
Handle warnings before propagating a primarySQLException
from executing the given statement.Calls regular
handleWarnings(Statement)
but catchesSQLWarningException
in order to chain theSQLWarning
into the primary exception instead.- Parameters:
stmt
- the current JDBC statementex
- the primary exception after failed statement execution- Since:
- 5.3.29
- See Also:
-
handleWarnings
Handle the warnings for the given JDBC statement, if any.Throws a
SQLWarningException
if we're not ignoring warnings, otherwise logs the warnings at debug level.- Parameters:
stmt
- the current JDBC statement- Throws:
SQLException
- in case of warnings retrieval failureSQLWarningException
- for a concrete warning to raise (when not ignoring warnings)- See Also:
-
handleWarnings
Throw aSQLWarningException
if encountering an actual warning.- Parameters:
warning
- the warnings object from the current statement. May benull
, in which case this method does nothing.- Throws:
SQLWarningException
- in case of an actual warning to be raised
-
translateException
protected DataAccessException translateException(String task, @Nullable String sql, SQLException ex) Translate the givenSQLException
into a genericDataAccessException
.- Parameters:
task
- readable text describing the task being attemptedsql
- the SQL query or update that caused the problem (may benull
)ex
- the offendingSQLException
- Returns:
- a DataAccessException wrapping the
SQLException
(nevernull
) - Since:
- 5.0
- See Also:
-