Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single on multiple DAO and Repository in Android Room database project?

I have a Room database project which has a DAO and a Repository (mediator between different data sources) for each table in the database. It is a lot files and class names to remember.

I would like to know if there a disadvantages for using a single Repository and DAO class per project?

like image 317
Blazej SLEBODA Avatar asked Dec 25 '18 13:12

Blazej SLEBODA


People also ask

Can a room database have more than one Dao?

There is no such rule that you have to make separate @Dao for every table. You can make one Dao class that holds all of your database queries. But just with the convention, you make separate Dao for every entity. This way your code will be organized, that's all.

What is Dao in room database in Android?

When you use the Room persistence library to store your app's data, you interact with the stored data by defining data access objects, or DAOs. Each DAO includes methods that offer abstract access to your app's database. At compile time, Room automatically generates implementations of the DAOs that you define.

What is repository in room database?

Repository: Repository is a class that is mainly used to manage multiple sources of data. Entity: Entity is an annotated class that is used to describe a database table when we are working with Room.


1 Answers

There is no such rule that you have to make separate @Dao for every table. You can make one Dao class that holds all of your database queries.

@Dao
interface MyDao{
    @Query("SELECT * FROM Student")
    fun getStudents(): List<User>

    @Query("SELECT * FROM Professors")
    fun getProfs(): List<User>
}

But just with the convention, you make separate Dao for every entity. This way your code will be organized, that's all. It's difficult to review your code if you have bunch of unrelated queries within the same Dao.

For repositories, I would have different approach. Although there is no such rule that you have to use separate Repository or single Repository, I would use both wherever I think the one is necessary.

For example, if I have only one database call from User table and one from Post table, I don't see point of having two separate repositories for each table. So I would just make single repository in a such case. But on the other hand, if I have 10 database calls from User table and 10 more from Post table, I would split repositories and have two repositories one for each table.

All in all, these are just conventions and above are just suggested style of coding.

like image 126
musooff Avatar answered Oct 01 '22 02:10

musooff