Retrieving Domain Objects with RowMapper<T>
Rather than retrieving a single value, most of the time you will want to query one or more rows and then
transform each row into the corresponding domain object.
Spring's RowMapper<T> interface (under the package org.springframework.jdbc.core) provides a
simple way for you to perform mapping from a JDBC resultset to POJOs. Let's see it in action by
implementing the findAll() method of the ContactDao interface using the RowMapper<T> interface.
Listing 8-28 shows the implementation of the findAll() method.
Listing 8-28. Use RowMapper<T> to Query Domain Objects
package com.apress.prospring3.ch8.dao.jdbc.xml;
// Import statements omitted
public class JdbcContactDao implements ContactDao, InitializingBean {
// Other methods omitted
public List<Contact> findAll() {
String sql = "select id, first_name, last_name, birth_date from contact";
return jdbcTemplate.query(sql, new ContactMapper());
}
private static final class ContactMapper implements RowMapper<Contact> {
public Contact mapRow(ResultSet rs, int rowNum) throws SQLException {
Contact contact = new Contact();
contact.setId(rs.getLong("id"));
contact.setFirstName(rs.getString("first_name"));
contact.setLastName(rs.getString("last_name"));
contact.setBirthDate(rs.getDate("birth_date"));
return contact;
}
}
}
In the previous listing, we define a static inner class called ContactMapper that implements the
RowMapper<T> interface. The class needs to provide the mapRow() implementation, which transforms the
values in a specific record of the resultset into the domain object you want. Making it a static inner class
allows you to share the RowMapper<T> among multiple finder methods.
Afterward, the findAll() method just needs to invoke the query method and pass in the query string
and the row mapper. In case the query requires parameters, the query() method provides a overload
that accepts the query parameters.
Let's add the following code snippet (Listing 8-29) into the testing program (the JdbcContactDaoSample
class).
Listing 8-29. Code Snippet for Listing Contacts
// Find and list all contacts
List<Contact> contacts = contactDao.findAll();
for (Contact contact: contacts) {
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home