3

我见过的大多数 DAO 示例都包含仅涉及一张表的简单查询。

我正在重构一个没有 DAO 的项目,该项目有很多使用多个表的 SQL 查询。我的问题是如何最好地为 DAO 设计模型?在下面的示例中,我可以创建一个涵盖每个特定查询的对象。但是,我不确定这是否是好的做法。例如,让一个对象代表每个数据库表会更好吗?

CustomerPaymentDAO 覆盖此查询:

select
    a.username,
    p.creation_date,
    p.amount,
    c.card_type
from
    account      a,
    payment      p,
    payment_type t,
    payment_card c
where
...

CustomerPurchaseDAO 覆盖此查询:

select
    a.username,
    i.name,
    i.cost,
    c.name,
    v.value
from
    account      a,
    item         i,
    category     c,
    voucher      v
where
...
4

1 回答 1

1

Generally speaking, there are two options:

  1. Create an entity corresponding to each table and specify necessary relationships (many-to-many, many-to-one, one-to-one).

  2. In the database create a view for each query, and create entities on per view basis (in your example - two views + two entities).

The second case is fine for read-only objects. If you need to create/update/delete entities then you need to create an entity corresponding to each single table.

于 2012-04-03T20:26:50.033 回答