What is the difference between Data Access Objects (DAO) and Repository patterns? I am developing an application using Enterprise Java Beans (EJB3), Hibernate ORM as infrastructure, and Domain-Driven Design (DDD) and Test-Driven Development (TDD) as design techniques.
DAO
is an abstraction of data persistence.
Repository
is an abstraction of a collection of objects.
DAO
would be considered closer to the database, often table-centric.
Repository
would be considered closer to the Domain, dealing only in Aggregate Roots.
Repository
could be implemented using DAO
's, but you wouldn't do the opposite.
Also, a Repository
is generally a narrower interface. It should be simply a collection of objects, with a Get(id)
, Find(ISpecification)
, Add(Entity)
.
A method like Update
is appropriate on a DAO
, but not a Repository
- when using a Repository
, changes to entities would usually be tracked by separate UnitOfWork.
It does seem common to see implementations called a Repository
that is really more of a DAO
, and hence I think there is some confusion about the difference between them.
IRepository
interface. You would want your repository to use DAO's in its implementation. Remember, a DAO will be a per-table object, whereas a Repository will almost always have to use multiple DAO's to build a single Entity. 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. –
Massenet Add(Entity)
as an example on Repository pattern. However the Repository is to abstract all persistance, hence it's inside the domain and works only with domain/business objects, not with Entities. A repository should not expose table representations (Entities) –
Surat OK, think I can explain better what I've put in comments :). So, basically, you can see both those as the same, though DAO is a more flexible pattern than Repository. If you want to use both, you would use the Repository in your DAO-s. I'll explain each of them below:
REPOSITORY:
It's a repository of a specific type of objects - it allows you to search for a specific type of objects as well as store them. Usually it will ONLY handle one type of objects. E.g. AppleRepository
would allow you to do AppleRepository.findAll(criteria)
or AppleRepository.save(juicyApple)
.
Note that the Repository is using Domain Model terms (not DB terms - nothing related to how data is persisted anywhere).
A repository will most likely store all data in the same table, whereas the pattern doesn't require that. The fact that it only handles one type of data though, makes it logically connected to one main table (if used for DB persistence).
DAO - data access object (in other words - object used to access data)
A DAO is a class that locates data for you (it is mostly a finder, but it's commonly used to also store the data). The pattern doesn't restrict you to store data of the same type, thus you can easily have a DAO that locates/stores related objects.
E.g. you can easily have UserDao that exposes methods like
Collection<Permission> findPermissionsForUser(String userId)
User findUser(String userId)
Collection<User> findUsersForPermission(Permission permission)
All those are related to User (and security) and can be specified under then same DAO. This is not the case for Repository.
Finally
Note that both patterns really mean the same (they store data and they abstract the access to it and they are both expressed closer to the domain model and hardly contain any DB reference), but the way they are used can be slightly different, DAO being a bit more flexible/generic, while Repository is a bit more specific and restrictive to a type only.
CarDescription
that has e.g. language_id
as foreign key - then to retrieve that I should do something like this: CarRepository.getAll(new Criteria(carOwner.id, language.id));
which would give me all cars of a language in a specific language - is that the right way to do it? –
Sorrow CarRepository.findByLanguageId(language.id)
and you wouldn't even need to write the code, you just define the interface with a method with that name and Spring Data takes care of building the default class implementation for you. Pretty neat stuff ;) –
Plural TodoReporitory
in another class that then implements those methods like MyRepository extends TodoRepository
where MyRepository
uses Hibernate for the persistence stuff. There is just sooo much information out there and I'm starting to get confused in the middle of a project where I already have a larger database and already a server/client communication –
Sorrow findById
). And you are practically done. What then Spring Data does is, it finds all these interfaces you've created which extend the Repository interface and creates the classes for you. You'll never see those classes and you won't be able to create new instances, but you don't need to as you can just autowire the interface and let Spring locate that repository object. –
Plural DAO and Repository pattern are ways of implementing Data Access Layer (DAL). So, let's start with DAL, first.
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 DAL.
So far, we haven't talked about any particular implementation: only a general principle that putting database access logic in a separate module.
Now, how we can implement this principle? Well, one know way of implementing this, in particular with frameworks like Hibernate, is the DAO pattern.
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.
Then what is Repository pattern? 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. What is meant by behaving like a collection is not that it has to be instantiated like . Instead, it means that it should support operations such as add, remove, contains, etc. This is the essence of Repository pattern.Collection collection = new SomeCollection()
In practice, for example in the case of using Hibernate, Repository pattern is realized with DAO. That is an instance of DAL can be both at the same an instance of DAO pattern and Repository pattern.
Repository pattern is not necessarily something that one builds on top of DAO (as some may suggest). If DAOs are designed with an interface that supports the above-mentioned operations, then it is an instance of Repository pattern. Think about it, If DAOs already provide a collection-like set of operations, then what is the need for an extra layer on top of it?
Frankly, this looks like a semantic distinction, not a technical distinction. The phrase Data Access Object doesn't refer to a "database" at all. And, although you could design it to be database-centric, I think most people would consider doing so a design flaw.
The purpose of the DAO is to hide the implementation details of the data access mechanism. How is the Repository pattern different? As far as I can tell, it isn't. Saying a Repository is different to a DAO because you're dealing with/return a collection of objects can't be right; DAOs can also return collections of objects.
Everything I've read about the repository pattern seems rely on this distinction: bad DAO design vs good DAO design (aka repository design pattern).
Repository is more abstract domain oriented term that is part of Domain Driven Design, it is part of your domain design and a common language, DAO is a technical abstraction for data access technology, repository is concerns only with managing existing data and factories for creation of data.
Check these links:
A DAO allows for a simpler way to get data from storage, hiding the ugly queries.
Repository deals with data too and hides queries and all that but, a repository deals with business/domain objects.
A repository will use a DAO to get the data from the storage and uses that data to restore a business object.
For example, A DAO can contain some methods like that -
public abstract class MangoDAO{
abstract List<Mango>> getAllMangoes();
abstract Mango getMangoByID(long mangoID);
}
And a Repository can contain some method like that -
public abstract class MangoRepository{
MangoDao mangoDao = new MangDao;
Mango getExportQualityMango(){
for(Mango mango:mangoDao.getAllMangoes()){
/*Here some business logics are being applied.*/
if(mango.isSkinFresh()&&mangoIsLarge(){
mango.setDetails("It is an export quality mango");
return mango;
}
}
}
}
This tutorial helped me to get the main concept easily.
The key difference is that a repository handles the access to the aggregate roots in a an aggregate, while DAO handles the access to entities. Therefore, it's common that a repository delegates the actual persistence of the aggregate roots to a DAO. Additionally, as the aggregate root must handle the access of the other entities, then it may need to delegate this access to other DAOs.
Repository are nothing but well-designed DAO.
ORM are table centric but not DAO.
There's no need to use several DAO in repository since DAO itself can do exactly the same with ORM repositories/entities or any DAL provider, no matter where and how a car is persisted 1 table, 2 tables, n tables, half a table, a web service, a table and a web service etc. Services uses several DAO/repositories.
My own DAO, let's say CarDao only deal with Car DTO,I mean, only take Car DTO in input and only return car DTO or car DTO collections in output.
So just like Repository, DAO actually is an IoC, for the business logic, allowing persitence interfaces not be be intimidated by persitence strategies or legacies. DAO both encapsulates the persistence strategy and does provide the domaine-related persitence interface. Repository is just an another word for those who had not understood what a well-defined DAO actualy was.
DAO provides abstraction on database/data files or any other persistence mechanism so that, persistence layer could be manipulated without knowing its implementation details.
Whereas in Repository classes, multiple DAO classes can be used inside a single Repository method to get an operation done from "app perspective". So, instead of using multiple DAO at Domain layer, use repository to get it done. Repository is a layer which may contain some application logic like: If data is available in in-memory cache then fetch it from cache otherwise, fetch data from network and store it in in-memory cache for next time retrieval.
Try to find out if DAO or the Repository pattern is most applicable to the following situation : Imagine you would like to provide a uniform data access API for a persistent mechanism to various types of data sources such as RDBMS, LDAP, OODB, XML repositories and flat files.
Also refer to the following links as well, if interested:
http://www.codeinsanity.com/2008/08/repository-pattern.html
http://blog.fedecarg.com/2009/03/15/domain-driven-design-the-repository/
http://devlicio.us/blogs/casey/archive/2009/02/20/ddd-the-repository-pattern.aspx
Per Spring documentation there is no clear difference:
The @Repository annotation is a marker for any class that fulfills the role or stereotype of a repository (also known as Data Access Object or DAO).
If we consider the original definitions of both design patterns DAO and Repository appear very similar. The main difference is the dictionary and the source from which they came (Oracle vs. Fowler).
Quote:
DAO - "separates a data resource's client interface from its data access mechanisms" and "The DAO implements the access mechanism required to work with the data source. The data source could be a persistent store like an RDBMS, an external service like a B2B exchange, a repository like an LDAP database, or a business service accessed via CORBA Internet Inter-ORB Protocol (IIOP) or low-level sockets."
Repository - "Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects." and "Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers."
Based on these citations, both design patterns mediate communication between the domain layer and the data layer. Moreover, Repository is associated with ORM and on the contrary DAO is a more generic interface for accessing data from anywhere.
DAOs might not always explicitly be related to Only DataBase,
It can be just an Interface to access Data, Data in this context might be accessed from DB/Cache or even REST (not so common these days, Since we can easily separate them in their respective Rest/IPC Clients),
Repo here in this approach be implemented by any of the ORM Solutions, If the underlying Cache/Repo Changes it'll not be propagated/impacts Service/Business Layers.
DAOs can accept/return Domain Types. Consider for a Student Domain, the associated DAO class will be StudentDao
StudentDao {
StudentRepository,
StudentCache,
Optional<Student> getStudent(Id){
// Use StudentRepository/StudentCache to Talk to DD & Cache
// Cache Type can be the same as Domain Type, DB Type(Entities) should be a Same/Different Type.
}
Student updateStudent(Student){
// Use StudentRepository/StudentCache to Talk to DD & Cache
// Cache Type can be the same as Domain Type, DB Type(Entities) should be a Same/Different Type.
}
}
DAOs can accept/return SubDomain Types. Consider a Student Domain, that has Sub Domain, say Attendance / Subject that will have a DAO class StudentDao,
StudentDao {
StudentRepository, SubjectRepository, AttendanceRepository
StudentCache, SubjectCache, AttendanceCache
Set<Subject> getStudentSubject(Id){
// Use SubjectRepository/SubjectCache to Talk to DD & Cache
}
Student addNewSubjectToStudent(ID, Subject){
// Use SubjectRepository/SubjectCache to Talk to DD & Cache
}
}
in a very simple sentence: The significant difference being that Repositories represent collections, whilst DAOs are closer to the database, often being far more table-centric.
© 2022 - 2024 — McMap. All rights reserved.