this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
Now let's see how to implement the method. Listing 8-26 shows the implementation.
Listing 8-26. Using NamedParameterJdbcTemplate to Retrieve a Single Value
package com.apress.prospring3.ch8.dao.jdbc.xml;
// Import statement omitted
public class JdbcContactDao implements ContactDao, InitializingBean {
// Other methods omitted
public String findLastNameById(Long id) {
String sql = "select last_name from contact where id = :contactId";
SqlParameterSource namedParameters =
new MapSqlParameterSource("contactId", id);
return namedParameterJdbcTemplate.queryForObject(sql,
namedParameters, String.class);
}
}
First, you will see that instead of the ? placeholder, the named parameter (prefix by a semicolon) was
used instead. Second, a SqlParameterSource was initialized, which is a Map-based SQL parameter source
with the key as the named parameter's name and the value as the value of the parameter. Instead of
SqlParameterSource, you can also simply construct a map for storing named parameters. Listing 8-27 is a
variant of the previous method.
Listing 8-27. Using NamedParameterJdbcTemplate to Retreive a Single Value
package com.apress.prospring3.ch8.dao.jdbc.xml;
// Import statement omitted
public class JdbcContactDao implements ContactDao, InitializingBean {
// Other methods omitted
public String findLastNameById(Long id) {
String sql = "select last_name from contact where id = :contactId";
Map<String, Object> namedParameters = new HashMap<String, Object>();
namedParameters.put("contactId", id);
return namedParameterJdbcTemplate.queryForObject(sql,
namedParameters, String.class);
}
}
To test the code, just add the method into the main testing class in Listing 8-25 and run it. I will skip
it here.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home