JDBCTemplate RowMapper for Nested POJOs

2

Let's say I have the following Pojos

public class Pedidos{
 private Strig codigo;
 private String nomePedido;
 private List<Dados> dadosPedido;
 //getters e setters}  
}

E

  public class Dados {
    private String nome;
    private int codigo;
 }

I know I could use a BeanPropertyRowMapper to populate a list of Orders objects, now is there any way to also populate the Data object through the same query? After that I would need to mount an XML where each Request would have its corresponding Data list, I found a similar question: link
But in my case I also have a List of Users.

    
asked by anonymous 27.02.2014 / 19:48

1 answer

1

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.

        
    27.02.2014 / 20:09