The official documentation states that:
It is recommended to have multiple Dao classes in your codebase depending on the tables they touch.
and that one can mark a method with the Transaction annotation like that:
@Dao
public abstract class ProductDao {
@Insert
public abstract void insert(Product product);
@Delete
public abstract void delete(Product product);
@Transaction
public void insertAndDeleteInTransaction(Product newProduct, Product oldProduct) {
// Anything inside this method runs in a single transaction.
insert(newProduct);
delete(oldProduct);
}
}
But what if a transaction spans multiple DAOs? Should I merge all DAOs into one just to support transactions, or there's a better way to do that?
You can use RoomDatabase.runInTransaction(...)
Something like:
database.runInTransaction(new Runnable(){
@Override
public void run(){
Access all your daos here
}
});