Contact contact = null;
while (rs.next()) {
Long id = rs.getLong("id");
contact = map.get(id);
if (contact == null) {  // new contact record
contact = new Contact();
contact.setId(id);
contact.setFirstName(rs.getString("first_name"));
contact.setLastName(rs.getString("last_name"));
contact.setBirthDate(rs.getDate("birth_date"));
contact.setContactTelDetails(new ArrayList<ContactTelDetail>());
map.put(id, contact);
}
// Process contact tel. detail (if exists)
Long contactTelDetailId = rs.getLong("contact_tel_id");
if (contactTelDetailId > 0) {
ContactTelDetail contactTelDetail = new ContactTelDetail();
contactTelDetail.setId(contactTelDetailId);
contactTelDetail.setContactId(id);
contactTelDetail.setTelType(rs.getString("tel_type"));
contactTelDetail.setTelNumber(rs.getString("tel_number"));
contact.getContactTelDetails().add(contactTelDetail);
}
}
return new ArrayList<Contact> (map.values());
}
}
}
The code looks quite like the RowMapper sample, but this time we declare an inner class that
implements ResultSetExtractor. Then we implement the extractData() method to transform the
resultset into a list of Contact objects accordingly. For the findAllWithDetail() method, the query uses a
left join to join the two tables so that contacts with no telephones will also be retrieved. The result is a
Cartesian product of the two tables. Finally, we use the JdbcTemplate.query() method, passing in the
query string and the resultset extractor.
Let's add the following code snippet (Listing 8-31) into the testing program (the
JdbcContactDaoSample class).
Listing 8-31. Code Snippet for Listing Contacts
// Find and list all contacts with details
List<Contact> contactsWithDetail = contactDao.findAllWithDetail();
for (Contact contact: contactsWithDetail) {
System.out.println(contact);
if (contact.getContactTelDetails() != null) {
for (ContactTelDetail contactTelDetail: contact.getContactTelDetails()) {
System.out.println("---" + contactTelDetail);
}
}
System.out.println();
}
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home