In Room
have 2 tables/Dao - PoolDao and AccountDao with relation one-to-many (one pool many accounts). I need first create and save pool and after create and save (one or more) accounts.
How in room create transaction which operates with two Dao? In documentation i find only transaction for only one dao - https://developer.android.com/reference/android/arch/persistence/room/Transaction
A DAO can be either an interface or an abstract class. If it’s an abstract class, it can optionally have a constructor that takes a RoomDatabase as its only parameter. Room creates each DAO implementation at compile time.
Transaction methods in room are methods marked with @Transaction annotation. Since you can not have non-abstract methods in interfaces, you need to use an abstract class instead of interface for DAO. Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.
Use transactions in a DAO Recordset. A transaction is a set of operations bundled together and handled as a single unit of work. The work in a transaction must be completed as a whole; if any part of the transaction fails, the entire transaction fails. Transactions offer the developer the ability to enforce data integrity.
@Transaction methods can also be suspending and they can call other suspending DAO functions: You can also call suspension functions from different DAOs inside a transaction: You can provide executors (by calling setTransactionExecutor or setQueryExecutor when you’re building your database) to control the threads they run on.
You can user runInTransaction option of your appDatabase object:
appDatabase.runInTransaction
{
appDatabase.dao1.doWhatNeedsToBeDone()
appDatabase.dao2.doWhatNeedsToBeDone()
}
You have example 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