Is it okay to bypass the repository pattern for complex queries?

前端 未结 3 661
无人及你
无人及你 2020-12-24 02:28

This is my understanding about DDD at the moment:

  • The strict repository pattern should only implement get(), delete() and create(), and maybe variants of get()
3条回答
  •  抹茶落季
    2020-12-24 03:17

    The strict repository pattern should only implement get(), delete() and create(), and maybe variants of get() where one can search or to retrieve an entire collection

    Repository interface is part of your domain and should be based on Ubiquitous Language as much as possible. All Repositories are different just like all your Aggregates are different. Strict, generic repositories are CRUD overgeneralization and may reduce code expressiveness. 'Create' method also does not belong to Repository because beginning of object life cycle is usually handled by Factory or Object itself. 'Add' seems like a better name when you want to persist existing object because Repository has a collection semantics.

    The question here is how to implement complex queries which involves many aggregate roots. For example, we have two aggregate roots - product and user. If I am doing a page which list what products a user have bought, then I have a query which stretch across both the user aggregate and the product aggregate.

    In this case you just have to listen to the business requirements, I emphasized the part that I think is most important. Based on that it looks like you need:

    Products products = /* get Products repository implementation */;
    IList res = products.BoughtByUser(User user);
    

    The idea of organizing code like that is to match business requirements and ubiquitous language as much as possible. The naming of the repository interfaces is also important, I prefer to have Products or AllProducts instead of ProductsRepository. Phil Calçado has a very good article on this subject, highly recommended.

    How should this query be implemented?
    

    There is nothing special about this query, it can be implemented just like all other queries in Products repository. The querying itself is hidden from Domain because Repository implementation belongs to Data Access layer. Data Access can implement any query because it has intimate knowledge of all the Aggregates and their relationships. At this point it would just be a Hibernate or SQL question.

提交回复
热议问题