What exactly is the difference between a data mapper and a repository?

前端 未结 2 1241
深忆病人
深忆病人 2020-12-23 14:41

Well I\'ve been trying to find out the difference between data mapper and repository, but up to now I still have not. It seems to me that the expert programmer said \"Reposi

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-23 15:27

    I realize that this answer is kind of late, but it may help someone in the future that stumbles upon this same question and finds that the available answer(s) do not quite answer the question (which I felt when I first came across this question).

    After having read PoEAA (Martin Fowler), I too was having trouble identifying the difference between a data mapper and a repository.

    This is what I've found that the 2 concepts ultimately boil down to:

    • a Repository acts like a collection of domain objects, with powerful querying capabilities (Evans, DDD)
    • a DataMapper "moves data between objects and a database while keeping them independent of each other and the mapper itself" (Fowler, PoEAA)

    Repositories are a generic concept and don't necessarily have to store anything to a database, its main function is to provide collection like (query-enabled) access to domain objects (whether they are gotten from a database is besides the point). Repositories may (and often will) contain DataMappers themselves.

    DataMappers serve as the middle layer between domain objects and a database, allowing them to evolve independently without any one depending on the other. Datamappers might have "find" or query functionality, but that is not really their main function. The more you find that you are using elaborate query logic in your DataMappers, the more you want to start thinking about decoupling that query logic into a repository while leaving your DataMappers to serve their main function, mapping domain objects to the database and vice versa.

提交回复
热议问题