对于一个新项目,我们决定使用Spring MVC和JdbcTemplate (特别是SimpleJdbcTemplate)来持久化域对象。我在这种方法中遇到的一个问题是如何从SELECT查询中干净地创建对象图。当我从单个表拉取行时,RowMapper机制似乎工作得很好;当我映射连接查询的结果时,我就开始担心了。
为了给出一个具体的(但完全是虚构的)示例,假设我有两个N对1关系的实体:
public class Invoice {
private Customer customer;
...
}
public class Customer {
private int id;
private String name;
...
}我希望能够在我的InvoiceDAO上调用一个selectInvoices()方法,并检索一个填充了完整形式的Customer实例的Invoice列表。
public class Invoice {
// this makes me unhappy
private int customerId;
...
}干净利落地实现这一目标的最佳实践是什么?我应该咬紧牙关使用ORM吗?
发布于 2012-03-04 01:56:32
这正是ORM擅长的。如果你想自己完成这一切,我的诀窍是使用一张地图来控制客户:
Map<Long, Customer> customersById = new HashMap<Long, Customer>();
...
public Invoice mapRow(ResultSet rs, int rowNum) throws SQLException {
Invoice invoice = ...
// populate invoice fields
Long customerId = rs.getLong("customerId");
Customer c = customersById.get(customerId);
if (c == null) {
// first time we meet this customer
c = ...
// populate customer fields from result set
customersById.put(customerId, c);
}
invoice.setCustomer(c);
}https://stackoverflow.com/questions/9548267
复制相似问题