Chapter 2. Advanced Concepts
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.
NamedParameterJdbcTemplate
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
?
variables:
select count(*) from TRADES where account = :account and security = :security
The :account
and :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
framework.
Using Map
The following snippet shows how to set the variables by using a map with keys:
public ...
Get Just Spring Data Access now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.