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?
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.
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.
You can use RoomDatabase.runInTransaction(...)
Something like:
database.runInTransaction(new Runnable(){ @Override public void run(){ Access all your daos here } });
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