RowMapper
is not a good solution for this.
I was here thinking about a gambiarra to store an internal map or something, but searching for an alternative, I found this code almost ready using ResultSetExtractor
:
jdbcTemplate.query("SELECT * FROM INVOICE inv JOIN INVOICE_LINE line " +
+ " on inv.id = line.invoice_id", new ResultSetExtractor<List<Invoice>>() {
List<Invoice> extractData(ResultSet rs) {
Map<Integer,Invoice> invoices = new HashMap<Integer,Invoice>();
while(rs.hasNext()) {
rs.next();
Integer invoiceId = rs.getInd("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();
}
});
Font
With ResultSetExtractor
you manually iterate over the query results. For each record:
Retrieve id
of the object in your main table ( Pedidos
)
Verify that Pedido
already exists on the map
2.1 If it does not exist, create the product and put it on the map
Retrieve information from table Dados
Add the data to the current product list
The end result is a product map, each with its data filled in. To return a list of products, use the keySet()
method of the map.