Bohsen
Bohsen

Reputation: 4350

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());
        }
    }
}

Upvotes: 12

Views: 1672

Answers (1)

Bohsen
Bohsen

Reputation: 4350

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.

Upvotes: 17

Related Questions