Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Room: DAOs with nested DAOs

Is there a way to add DAOs as dependencies in other DAOs with Android Room Persistence Library, maybe by using Dagger2? I'm trying to avoid method explosion in a DAO class that does operations on multiple tables using transactions.

This is what I'm trying to accomplish.

Example: FooBarRepository.class

@Dao
public abstract class FooBarRepository {
    // THESE ARE DAOs ADDED AS DEPENDENCIES
    FooRepository fooRepository;
    BarRepository barRepository;

    ...

    @Transaction
    public void insertOrUpdateInTransaction(FooBar... foobars) {
        for (FooBar item : foobars) {
            fooRepository.insertOrUpdateInTransaction(item.getFoo());
            barRepository.insertOrUpdateInTransaction(item.getBar());
        }
    }
}
like image 857
Bohsen Avatar asked Oct 16 '17 09:10

Bohsen


People also ask

Can a room database have multiple 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.

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 Dao in room?

android.arch.persistence.room.Dao. Marks the class as a Data Access Object. Data Access Objects are the main classes where you define your database interactions. They can include a variety of query methods. The class marked with @Dao should either be an interface or an abstract class.


1 Answers

Finally found the solution:

@Dao
public abstract class Repository {

    private final TaskRepository taskRepository;
    private final ResourceRepository resourceRepository;

    public Repository(AppDatabase database) {
        this.taskRepository = database.getTaskRepository();
        this.resourceRepository = database.getResourceRepository();
    }
...

This is allowed because a dao-object can take the database as a constructor parameter.

like image 85
Bohsen Avatar answered Oct 11 '22 15:10

Bohsen