The Spring framework has provided extensive APIs to work with the database. We’ve covered
the basics of the framework in the last chapter, especially using the versatile
JdbcTemplate class. This chapter elaborates on advanced concepts,
including other templates, callbacks, and batch operations.
In our queries, we define the bind variables using a
? operator as
shown in the following snippet:
select count(*) from TRADES where account = ? and security = ?
If we have a handful of these parameters, it would be an eyesore to read a query with
all over the place. Spring has defined a new
NamedParameterJdbcTemplate class that comes handy in eliminating these
placeholder variables. This class basically encapsulates the
JdbcTemplate by providing the enhanced functionality of declaring the bind
variables using named parameters.
The same query can be tweaked as shown below using appropriate names instead of
select count(*) from TRADES where account = :account and security = :security
:security names indicate that these variables will be passed in by some means.
Note the colon
before the variable; this is the syntax you must follow.
There are two ways of setting these variables. One is to use a simple
Map with the variables as the keys, and the other is to use
SqlParameterSource, a utility provided by the
The following snippet shows how to set the variables by using a map with keys: