使用SimpleJdbcTemplate清晰地创建域对象的对象图

时间:2012-03-03 17:39:53

标签: java spring jdbctemplate

对于一个新项目,我们决定使用Spring MVC和JdbcTemplate(特别是SimpleJdbcTemplate)来持久保存域对象。我用这种方法遇到的一个问题是如何从SELECT查询中干净地创建对象图。当我从单个表中提取行时,RowMapper机制似乎工作得很好;当我映射JOIN查询的结果时,我开始担心。

为了给出一个具体(但完全捏造)的例子,假设我有两个以N对1关系的实体:

public class Invoice {
    private Customer customer;
    ...
}

public class Customer {
    private int id;
    private String name;
    ...
}

我希望能够在selectInvoices()上调用InvoiceDAO方法,并检索填充了完整Invoice个实例的Customer列表。相反,我发现自己很想做类似以下的事情:

public class Invoice {
    // this makes me unhappy
    private int customerId;
    ...
}

干净利落地实现这一目标的最佳做法是什么?我应该咬紧牙关并使用ORM吗?

1 个答案:

答案 0 :(得分:2)

这正是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);
}