6.14.2010

Spring Note: NamedParameterJdbcTemplate

While I've been using Spring in various capabilities for some time now, I've never run across a situation where I've needed to execute a sql query with a duplicated parameter from code utilizing Spring. The following is a simple example of the type of query I ran into:

--Query Version 1
select * from table_1 where ID = ?
union
select * from table_2 where ID = ?

Using the normal JdbcTemplate.query method with this query would require you to create a two-element array which contains the same value in both elements. Silly DRY violation, right? Luckily, some of the folks behind the Spring JDBC packages decided to include a way to define queries where the values of parameters can be specified by name rather than by index. Here's an example using the named parameter syntax handled by the NamedParameterJdbcTemplate class:

...
final String query = "select * from table_1 where ID = :id"
        + " union"
        + " select * from table_2 where ID = :id"

final Map<String, String> params = new HashMap<String, String>();
params.put("id", id);

final RowMapper mapper = new ExampleRowMapper();

// jdbcTemplate is an instance of NamedParameterJdbcTemplate which
// has been created in the Spring ApplicationContext using an
// appropriately-created DataSource.
final List results = jdbcTemplate.query(query, params, mapper);
...

Interesting note:


After digging through the Spring's SVN repository, I found that the NamedParameterJdbcTemplate class does not appear to rely on the CallableStatement class for supporting the named parameter functionality. That means that using this class should be safe for all JDBC drivers(which support PreparedStatements), as the named parameters are handled above the JDBC driver's level.

No comments: