System.out.println(contact);
if (contact.getContactTelDetails() != null) {
for (ContactTelDetail contactTelDetail:
contact.getContactTelDetails()) {
System.out.println("---" + contactTelDetail);
}
}
System.out.println();
}
Running the program yields the following result (other outputs were omitted):
Contact - Id: 1, First name: Clarence, Last name: Ho, Birthday: 1980-07-30
Contact - Id: 2, First name: Scott, Last name: Tiger, Birthday: 1990-11-02
Contact - Id: 3, First name: John, Last name: Smith, Birthday: 1964-02-28
Retrieving Nested Domain Objects with ResultSetExtractor
Let's proceed to a bit more complicated example, in which we need to retrieve the data from the parent
(CONTACT) and child (CONTACT_TEL_DETAIL) table with a join and transform the data back into the nested
object (ContactTelDetail within Contact) accordingly.
The previously mentioned RowMapper<T> is suitable only for row base mapping to a single domain
object. For a more complicated object structure, we need to use the ResultSetExtractor interface. To
demonstrate its use, let's add one more method, findAllWithDetail(), into the ContactDao interface. The
method should populate the list of contacts with their telephone details.
public List<Contact> findAllWithDetail();
Listing 8-30 shows the implementation of the findAllWithDetail() method using
ResultSetExtractor.
Listing 8-30. Use ResultSetExtractor to Query Domain Objects
package com.apress.prospring3.ch8.dao.jdbc.xml;
// Import statements omitted
public class JdbcContactDao implements ContactDao, InitializingBean {
public List<Contact> findAllWithDetail() {
String sql = "select c.id, c.first_name, c.last_name, c.birth_date" +
", t.id as contact_tel_id, t.tel_type, t.tel_number from contact c " +
"left join contact_tel_detail t on c.id = t.contact_id";
return jdbcTemplate.query(sql, new ContactWithDetailExtractor());
}
private static final class ContactWithDetailExtractor implements
ResultSetExtractor<List<Contact>> {
public List<Contact> extractData(ResultSet rs) throws SQLException,
DataAccessException {
Map<Long, Contact> map = new HashMap<Long, Contact>();
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home