Fact 1:
Using @Transaction on a method causes the method to be overriden in the Dao_Impl generated class. This method looks like this:
@Override
public void makeFieldInactive(final long fieldId) {
__db.beginTransaction();
try {
MyDao_Impl.super.makeFieldInactive(fieldId);
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
}
}
Fact 2:
The runInTransaction() method looks like this:
/**
* Executes the specified {@link Runnable} in a database transaction. The transaction will be
* marked as successful unless an exception is thrown in the {@link Runnable}.
* <p>
* Room will only perform at most one transaction at a time.
*
* @param body The piece of code to execute.
*/
@SuppressWarnings("deprecation")
public void runInTransaction(@NonNull Runnable body) {
beginTransaction();
try {
body.run();
setTransactionSuccessful();
} finally {
endTransaction();
}
}
Conclusion:
They both do the same thing.
More Info:
I have done some testing and it appears that using either of them (or both, redundantly) will successfully cause your you Dao method to run in one transaction.
Answer:
Using @Transaction on a method that makes changes in multiple Daos that access the same database is a safe way to make sure that all database operations that happen in the method occur in one transaction.
Edit:
Example of accessing multipe Dao's in one method marked with @Transactoin:
@Transaction
public void addItem(ItemEntity item) {
item.setId(insert(item));
ItemReportDao itemReportDao = AppDatabase.getIntance().itemReportDao();
itemReportDao.addItemReport(item.getId());
}