首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用SimpleJdbcTemplate干净地创建域对象的对象图

使用SimpleJdbcTemplate干净地创建域对象的对象图
EN

Stack Overflow用户
提问于 2012-03-04 01:39:53
回答 1查看 1.2K关注 0票数 2

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

为了给出一个具体的(但完全是虚构的)示例,假设我有两个N对1关系的实体:

代码语言:javascript
复制
public class Invoice {
    private Customer customer;
    ...
}

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

我希望能够在我的InvoiceDAO上调用一个selectInvoices()方法,并检索一个填充了完整形式的Customer实例的Invoice列表。

代码语言:javascript
复制
public class Invoice {
    // this makes me unhappy
    private int customerId;
    ...
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-03-04 01:56:32

这正是ORM擅长的。如果你想自己完成这一切,我的诀窍是使用一张地图来控制客户:

代码语言:javascript
复制
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);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9548267

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档