public class Invoice{
private String docNum;
private String customer;
private ArrayList<InvoiceDetails> invoiceDetails;
/* Getters and setters*/
}
还有另外一个POJO
public class InvoiceDetails{
private String taxRate;
private Double taxAmount;
private Double amount;
/* Getters and setters*/
}
我想知道的是从结果集中填充Pojo Invoice
的最佳方法:
String sql= "SELECT InvoiceNumber, Customer, TaxRate, TaxAmount,Amount FROM TAX_VIEW WHERE Date=?"
PreparedStatement pst = cn.prepareStatement(Config.SQL_FACTURAS, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
pst.setDate(1, date);
ResultSet rs = pst.executeQuery();
假设ResultSet
可以为同一张发票返回多条记录,是否可以一劳永逸地执行此操作,而无需进行第二次迭代?
非常感谢
答案 0 :(得分:1)
在您看来,我猜已经有了加入。我想Invoice.docNum与SELECT中的InvoiceNumber相同。 (为什么有不同的名字?) 所以,你应该添加一个&#34; ORDER BY InvoiceNumber&#34;选择,并在处理循环中验证它的变化。代码是伪的,未经过测试:
ResultSet rs = pst.executeQuery();
Invoice invoice=new Invoice();
while(rs.next()){
if (invoice.getDocNum().compareTo(rs.getString(1))!=0) {
// This is a new Invoice, so process previous if not the first one
// and create a new instance
invoice=new Invoice();
invoice.setDocNum(rs.getString(1));
invoice.setCustomer(rs.getString(2));
invoice.setInvoiceDetails(new ArrayList<InvoiceDetails>());
}
InvoiceDetails invoiceDetails = new InvoiceDetails();
invoiceDetails.setTaxRate(rs.getString(3));
// ... further member settings, and finally add to list:
invoice.getInvoiceDetails.add(invoiceDetails);
}
// finally process the last Invoice if it is not empty