简体   繁体   中英

Android Studio Room Persistence - Should each entity have a seperate DAO, and how does that effect the repository class?

If I have a Database(DB) containing two tables/entities (A and B), should I make a DAO for each entity? (Ie DAO_A and DAO_B), Or do I make a DAO for the whole DB containing these two tables?

Then as regards the repository, will this be a repository for the whole Database(whole of DB) or just a repository for the database with only the relevant DAO's I want the class for (ie DAO_A and DAO_B). (Realy what I think I am asking here is will the Database have multiple repositories or just one repository, and will each entity have to have its own DAO, or can I make a general D

I would say go for every entity has its own DAO. Why? Because you properly separate them.

Let's say you would have a DAO which contains Entity A and B. In your repository you might only need Entity A, then it would not make any sense that this DAO uses Entity B as well. If a case occurs, where you need both Entities, just use both DAO's. A further reason for seperate DAO's is that you don't know how to couple Entities properly. How are you going to decide which Entities to couple into a DAO? Yes you could decide this depending on the Repository which makes use of it, but this can lead to code duplication (two DAO's make use of the same Entity, but each of those also use a second one - which is different for each DAO).


Regarding your second question: I believe it depends on your architecture how exactly your repository should be modeled.

For example when using MVVM:

Requirement: You have an Activity just displaying a list of images fetched from somewhere.

Then your ViewModel would offer a function like getAllImageModels or something similar. Each of those ImageModels would include an image (which will be displayed). Inside this function the Repository is called either an API call to retrieve a list of images to download or a database call to retrieve the list from the database (depending on internet connection). These images must be downloaded as well. Again images could be loaded from your local cache or downloaded via the API. Then the ViewModel wraps them in the desired model required by the View and thats it.

As you can see by this simple example, the Repository on its own just performs requests. Either to the local filesystem, database or API. It could have functions like getImageListFromDb and getImageListFromAPI in it. So that the classes which make use of it just have to decide when to use what.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM