Spring JDBC RowMapper usage for eager fetches

后端 未结 4 1592
执念已碎
执念已碎 2020-12-14 10:26

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

4条回答
  •  青春惊慌失措
    2020-12-14 11:33

    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();
        }
    
    
    });
    

提交回复
热议问题