我正在使用spring jdbc模板项目。在那里,我想从一个到多个关系加载所有记录。以下是我的数据库结构
class ReceiptHeader{
int rcptid,
String rcptname;
List<ReceiptDetails> receiptDetails;
}
class ReceiptDetails{
int detid;
String comment;
}
我想将ReceiptHeader中的所有记录加载到列表&lt;&gt;并且所有的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
答案 0 :(得分:0)
使用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;
}
});
答案 1 :(得分:0)
最后我找到了解决方案, 我错过了一些语法错误。
任何方式使用匿名类来获取数据并不是一个好习惯。
{{1}}