对于一个新项目,我们决定使用 Spring MVC 和 JdbcTemplate(特别是 SimpleJdbcTemplate)来持久化域对象。我在使用这种方法时遇到的一个问题是如何从 SELECT 查询干净地创建对象图。当我从单个表中提取行时,RowMapper 机制似乎工作得很好;当我映射 JOIN 查询的结果时,我变得很担心。
举一个具体的(但完全是捏造的)例子,假设我有两个处于 N 对 1 关系的实体:
public class Invoice {
private Customer customer;
...
}
public class Customer {
private int id;
private String name;
...
}
我希望能够在我的 InvoiceDAO
上调用 selectInvoices()
方法,并检索已填充的 Invoice
列表具有完整的 Customer
实例。相反,我发现自己想做如下的事情:
public class Invoice {
// this makes me unhappy
private int customerId;
...
}
干净地实现这一点的最佳实践是什么?我应该硬着头皮使用 ORM 吗?
最佳答案
这正是 ORM 所擅长的。如果你想自己做,我的技巧是用 map 来容纳客户:
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);
}
关于java - 使用 SimpleJdbcTemplate 干净地创建域对象的对象图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9548267/