Home > Blockchain >  Why do we need to use DAO and Repository in the same time on Android Project?
Why do we need to use DAO and Repository in the same time on Android Project?

Time:03-09

I am working on a path project to learn Android deeply but I am really confuse about implemantation of dao and repository. What is the difference between dao and repository on android. Is repository a common pattern ?

https://github.com/basaransuleyman/KetgoMVVM

CodePudding user response:

Repository is a common pattern. See https://www.martinfowler.com/eaaCatalog/repository.html. A Data Access Object (DAO) defines the interface for how to perform CRUD operations on a particular entity. A Repository can have several DAOs.

See also https://developer.android.com/training/data-storage/room/accessing-data

CodePudding user response:

Room is a layer over the SQLite database.

DAO forms the main component of the Room Persistence Library. We use queries to perform CRUD operations on the database(Insert,Update,Delete and Create). And DAO is the place, where we add such queries to perform operations. Inside a DAO we define methods.

On the other hand, a repository class is something that abstracts access to multiple databases. Although it is not part of the Architecture Component libraries, but is used as a best practice.

Example: Let say there is a Person Database , with a single table Person(known as entity).

For this example, we want to perform the following operations on the Person table:

  1. Insertion
  2. Update
  3. Read

For all the operations, we need to write queries. Those queries are meant to be written under a DAO class, here PersonDao

@Dao
interface PersonDao {
   @Insert
   suspend fun insertPerson(person1 : PersonModel)

   @Update
   suspend fun updatePerson(persone1 : PersonModel)

   @Query(SELECT * FROM person)
   fun getAllPerson() : LivaData<List<PersonModel>>
}

Here, PersonModel is a model class to store the Person entity. Next time, if we need to get the access to the Person table, we will implement the methods of the PersonDao. For example, like this:

     private val personDao : PersonDao
     private val personList : LiveData<List<PersonModel>>
     init{
       personList = personDao.getAllPerson()
     }

But wait, what if we have multiple database, we have to create a lot of DAO objects, which would make the code redundant, and prone to errors. So as to avoid that, we define a Repository.

class PersonRepository (private val personDao : PersonDao){
    
      suspend fun insertPerson(person1 : PersonModel) =
          personDao.insertPerson(person1)

      
      suspend fun updatePerson(person1 : PersonModel) =
          personDao.updatePerson(person1)
     
      
      fun getAllPerson() : LiveData<List<PersonModel>> = personDao.getAllPerson()

}
  • Related