img
Note In the Spring Jdbc module, there is a class called JdbcDaoSupport. It wraps the JdbcTemplate class,
and you can have your DAO classes extend the JdbcDaoSupport class. In this case, when the DAO class is
injected with the data source, the JdbcTemplate will be initialized automatically.
Retrieving Single-Value-Use JdbcTemplate Class
Let's start with a simple query that returns a single value. For example, we want to be able to retrieve the
first name of a contact by its ID. Let's add the method into the ContactDao interface first:
public String findFirstNameById(Long id);
Using JdbcTemplate, we can retrieve the value easily. Listing 8-24 shows the implementation of the
findFirstNameById() method in the JdbcContactDao class. For other methods, empty implementations
were created.
Listing 8-24. Using JdbcTemplate to Retrieve a Single Value
package com.apress.prospring3.ch8.dao.jdbc.xml;
// Import statement omitted
public class JdbcContactDao implements ContactDao, InitializingBean {
public String findFirstNameById(Long id) {
String firstName = jdbcTemplate.queryForObject(
"select first_name from contact where id = ?",
new Object[]{id}, String.class);
return firstName;
}
public List<Contact> findAll() {
return null;
}
public List<Contact> findByFirstName(String firstName) {
return null;
}
public void insert(Contact contact) {
}
public void update(Contact contact) {
}
public void delete(Long contactId) {
}
}
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home