The question is about the best practice usage for RowMapper in master/detail scenarios where we want to eagerly fetch details using spring jdbc.
Assume that we have
The ResultSetExtractor is a better option for doing this. Execute one query that joins both the tables and then iterate through the result set. You will need to have some logic to aggregate multiple rows belonging to the same invoice - either by ordering by invoice id and checking when the id changes or using a map like shown in the example below.
jdbcTemplate.query("SELECT * FROM INVOICE inv JOIN INVOICE_LINE line " +
+ " on inv.id = line.invoice_id", new ResultSetExtractor>() {
public List extractData(ResultSet rs) {
Map invoices = new HashMap();
while(rs.hasNext()) {
rs.next();
Integer invoiceId = rs.getInt("inv.id");
Invoice invoice = invoces.get(invoiceId);
if (invoice == null) {
invoice = invoiceRowMapper.mapRow(rs);
invoices.put(invoiceId,invoice);
}
InvoiceItem item = invLineMapper.mapRow(rs);
invoice.addItem(item);
}
return invoices.values();
}
});