Jdbctemplate Rowmapper for Nested Pojos

Asked

Viewed 577 times

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}  
}

And

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

I know I could use a Beanpropertyrowmapper to popular a list of Requests objects, now there is some form of also popular the Data object through the same query? After that I would need to assemble an XML where each Request would have its corresponding Data list, I found a similar question: https://stackoverflow.com/questions/16718163/jdbctemplate-set-nested-pojo-with-beanpropertyrowmapper
But in my case I also have a Users List.

1 answer

1


The RowMapper is not a good solution for this.

I was thinking here of a gambiarra to store an internal map or something like that, but searching for an alternative, I found this code practically ready using the 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();
    }


});

Source

With the ResultSetExtractor you do the manual iteration on the query results. For each record:

  1. Recover the id the object of its main table (Pedidos)
  2. Check whether the Pedido already exists on the map 2.1 If it does not exist, create the product and place it on the map
  3. Retrieve information from the table Dados
  4. Add the data to the current product list

The final result is a map of products, each with the respective data filled. To return a list of products, use the method keySet() of the map.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.