我正在春季jdbc模板项目中工作。我想从一对多关系中加载所有记录。以下是我的数据库结构,class ReceiptHeader{ int rcptid, String rcptname; List<ReceiptDetails> receiptDetails;}class ReceiptDetails{ int detid; String comment;}我想将ReceiptHeader中的所有记录加载到list ,并且所有ReceiptDetails记录都必须附加到该列表。我的代码是@Override public <E, U, V> List<E> getData(U param, V invId) throws Exception { List<ReceiptHdr> result = null; try { logger.info("--------Excute getData -->"); JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource); final Map<Integer, ReceiptHdr> rcptHdr = new HashMap<Integer, ReceiptHdr>(); jdbcTemplate.query("select h.rcpt_id, h.remark, d.det_id, d.comment from receipt_hdr h inner join receipt_det on h.rcpt_id = d.rcpt_id", new RowMapper<ReceiptDet>() { public ReceiptHdr mapRow(ResultSet rs, int rowNum) throws SQLException { Integer rcptId = rs.getInt("rcpt_id"); ReceiptHdr rcptHeader = (ReceiptHdr) rcptHdr.get(rcptId); if (rcptHeader == null) { String hdrRemark = rs.getString("remark"); rcptHeader = new ReceiptHdr(); rcptHeader.setRcptId(rcptId); rcptHeader.setHdrRemark(hdrRemark); rcptHdr.put(rcptId, rcptHeader); } ReceiptDet rcptDet = new ReceiptDet(); rcptDet.setRcptDetId(rs.getInt("det_id")); rcptDet.setDeleteComment(rs.getString("comment")); rcptHeader.getReceiptDets().add(rcptDet); return rcptDet; } }); result = new ArrayList<ReceiptHdr>(rcptHdr.values()); logger.info("--------Excute ReceiptHdr -->" + rcptHdr); } catch (Exception e) { logger.error("Error : Get Data-->" + e); } return (List<E>) result; }The screen shot of the code is here我尝试了以下两种方法,但没有成功,this link (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 将JdbcTemplate的重载query方法与ResultSetExtractor一起使用。public <T> T query(String sql, ResultSetExtractor<T> rse) throws DataAccessException永远不要访问和修改匿名类中的数据。这不是一个好习惯。 final Map<Integer, ReceiptHdr> rcptHdr = jdbcTemplate.query("select h.rcpt_id, h.remark, d.det_id, d.comment from receipt_hdr h inner join receipt_det on h.rcpt_id = d.rcpt_id", new ResultSetExtractor<Map<Integer, ReceiptHdr>>() { public Map<Integer, ReceiptHdr> extractData(ResultSet rs) throws SQLException, DataAccessException { Map<Integer, ReceiptHdr> rcptHdr = new HashMap<Integer, ReceiptHdr>(); while(rs.next()) { Integer rcptId = rs.getInt("rcpt_id"); ReceiptHdr rcptHeader = (ReceiptHdr) rcptHdr.get(rcptId); if (rcptHeader == null) { String hdrRemark = rs.getString("remark"); rcptHeader = new ReceiptHdr(); rcptHeader.setRcptId(rcptId); rcptHeader.setHdrRemark(hdrRemark); rcptHdr.put(rcptId, rcptHeader); } ReceiptDet rcptDet = new ReceiptDet(); rcptDet.setRcptDetId(rs.getInt("det_id")); rcptDet.setDeleteComment(rs.getString("comment")); rcptHeader.getReceiptDets().add(rcptDet); } return rcptHdr; } }); (adsbygoogle = window.adsbygoogle || []).push({});
07-25 22:34