首页 文章

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

提问于
浏览
2

对于一个新项目,我们决定使用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吗?

1 回答

  • 2

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

相关问题