private SelectContactByFirstName selectContactByFirstName;
@Resource(name="dataSource")
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
selectAllContacts = new SelectAllContacts(dataSource);
selectContactByFirstName = new SelectContactByFirstName(dataSource);
}
public List<Contact> findByFirstName(String firstName) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("first_name", firstName);
return selectContactByFirstName.executeByNamedParam(paramMap);
}
// Other code omitted
}
In Listing 8-39, upon data source injection, an instance of SelectContactByFirstName is constructed
(note the lines in bold). Afterward, in the findByFirstName() method, a HashMap is constructed with the
named parameters and values. Finally, the executeByNamedParam() method (inherited from SqlQuery<T>
abstract class indirectly) is called. To test the method, add the code snippet in Listing 8-40 into the
AnnotationJdbcDaoSample class.
Listing 8-40. Testing the findByFirstName() Method
// Find contacts by first name
contacts = contactDao.findByFirstName("Clarence");
listContacts(contacts);
Running the program will produce the following output from the findByFirstName() method:
Contact - Id: 1, First name: Clarence, Last name: Ho, Birthday: 1980-07-30
One point worth noting here is that MappingSqlQuery<T> is suitable only for mapping a single row to
a domain object. For a nested object, you still need to use JdbcTemplate with ResultSetExtractor like the
example method findAllWithDetail() presented in the JdbcTemplate class section.
Updating Data Using SqlUpdate
For updating data, Spring provides the SqlUpdate class. Listing 8-41 shows the UpdateContact class that
extends the SqlUpdate class for update operation.
Listing 8-41. The UpdateContact Class
package com.apress.prospring3.ch8.dao.jdbc.annotation;
import java.sql.Types;
import javax.sql.DataSource;
import org.springframework.jdbc.core.SqlParameter;
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home