← 返回刚才阅读的位置

知识卡片

普通读书笔记卡 · 1971.o.3.a.1.b.1.a.2.b.1

规格查询避免把表结构泄入领域层

理解等级:中级

原书先让 Specification.asSQL() 直接产 SQL,以示意规则与查询复用;随后指出表结构因此泄入领域层。改法是映射框架在基础设施层生成 SQL,或让 Specification 选择 Repository 的专门查询方法,SQL 留在仓储侧。后一方案会使仓储出现专用查询,属于可接受但需评估的取舍,不能把示意代码当最终推荐架构。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《Domain-Driven Design: Tackling Complexity in the Heart of Software》第70章《How to Model Less Obvious Kinds of Concepts》,Selection (or Querying),图9.15(源文件:_epub-src/0321125215_ch09lev1sec2_split_000.html) - 结论依据:原文明确指出直接在规格中写 SQL 的层次泄漏及映射维护风险。 - 原始内容:Here is a simple example, in which the query is encapsulated in the same class as the validation rule. A single method is added to the Invoice Specification and is implemented in the Delinquent Invoice Specification subclass: [...] Now this design has some problems. Most important, the details of the table structure have leaked into the DOMAIN LAYER ; they should be isolated in a mapping layer that relates the domain objects to the relational tables. Implicitly duplicating that information here could hurt the modifiability and maintainability of the Invoice and Customer objects, because any change to their mappings now have to be tracked in more than one place. [...] Some object-relational mapping frameworks provide the means to express such a query in terms of the model objects and attributes, generating the actual SQL in the infrastructure layer. [...] When the infrastructure doesn't come to the rescue, we can refactor the SQL out of the expressive domain objects by adding a specialized query method to the Invoice Repository . [...] This puts the SQL in the REPOSITORY , while the SPECIFICATION controls what query should be used. The rules aren't as neatly collected into the SPECIFICATION , but the essential declaration is there of what constitutes delinquency (that is, past grace period). The REPOSITORY now has a very specialized query that most likely will be used only in this case. That is acceptable, but depending on the relative numbers of Invoices that are overdue compared to those that are delinquent, an intermediate solution that leaves the REPOSITORY methods more generic may still give good performance, while keeping the SPECIFICATION more self-explanatory. - 示例代码节选:书中首先在 `Invoice Specification` 加 `asSQL()`,直接拼 `INVOICE`、`CUSTOMER` 表查询;后来以 `satisfyingElementsFrom(InvoiceRepository)` 控制调用,SQL 留在 `InvoiceRepository.selectWhereGracePeriodPast(...)`。两段代码均在同一 XHTML。