A Repository can cover a Dao, since it allows you to access/persist data, but the repository has a more precise definition based on simulating interaction with a collection of data.
same
Object-oriented applications that access a database, must have some logic to handle database access. In order to keep the code clean and modular, it is recommended that database access logic should be isolated into a separate module. In layered architecture, this module is Data Access Layer (DAL).
数据库交互的逻辑必须独立出来,无需业务层关心细节,保持app架构清晰简洁
DAO and Repository pattern are both ways of implementing DAL. So, let's start with DAL, first.
DAO and Repository是DAL的两种具体实现
DAO pattern is a way of generating DAL, where typically, each domain entity has its own DAO. For example, User
and UserDao
, Appointment
and AppointmentDao
, etc.
An example of DAO with Hibernate: http://gochev.blogspot.ca/2009/08/hibernate-generic-dao.html.
Like DAO, Repository pattern is also a way achieving DAL. The main point in Repository pattern is that, from the client/user perspective, it should look or behave as a collection.
Suppose you're modeling a pet shop and you have a table PetType
with different animals and their attributes (name: "Cat", type: "Mammal", etc.)
referenced by a table Pet
of the concrete pets you have in the shop (name: "Katniss", breed: "Calico", etc.)
. If you want to add an animal of a type not already in the database, you could use a repository to group the two separate DAO calls (one to create PetType
and the other for the Pet
) in one method, avoiding coupling in DAOs
difference
abstraction
DAO is an abstraction of data persistence.
Repository is an abstraction of a collection of objects.
position
DAO would be considered closer to the database, often table-centric.
Repository would be considered closer to the business domain, dealing only in Aggregate Roots.
this is like what described above
operating value
A DAO returns data by its very definition (a data access object).
A Repository, by its definition, returns domain aggregated objects.
Repository could be implemented using DAO's, but you wouldn't do the opposite. It should be simply a collection of objects, with a Get(id), Find(ISpecification), Add(Entity).
Remember, a DAO will be a per-table object, whereas a Repository will almost always have to use multiple DAO's to build some aggregated objects. If you find that is not the case, that your Repository and Entity only need to access a single table, then you are most likely building an anemic domain.
总结
DAO就是单纯的db操作封装,与业务逻辑无关。通常一个db table对应一个dao object
Repository是带有业务逻辑的数据操作封装,与业务逻辑强相关,是DDD中提出的概念。通常一个repo暴露的单个method就涉及多方数据的操作
网友评论