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());
}
}
}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With