Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Room transactions across DAOs

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?

like image 552
Alessandro Avatar asked Jan 09 '18 08:01

Alessandro


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?

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

You can use RoomDatabase.runInTransaction(...)

Something like:

database.runInTransaction(new Runnable(){   @Override   public void run(){     Access all your daos here   } }); 
like image 54
Martin Ohlin Avatar answered Sep 27 '22 22:09

Martin Ohlin