Android Room 数据库事务 [英] Android Room database transactions
问题描述
使用 Android 中的新房间数据库,我有一个需要进行两个顺序操作的要求:
With the new Room Database in Android, I have a requirement where there are two sequential operations that needs to be made:
removeRows(ids);
insertRows(ids);
如果我运行它,我看到(在检查数据库时)缺少一些行 - 我假设它们在插入后被删除.即第一个操作与第二个操作并行运行.
If I run this, I see (on examining the db) that there are some rows missing - I assume they are being deleted after inserting. viz. the first operation is running in parallel to the second.
如果我使用事务块,例如这样,那么一切都很好 - 第一个操作似乎在执行第二个操作之前完成:
If I use a transaction block, such as this, then it's all fine - the first operation seems to complete before doing the second:
roomDb.beginTransaction();
removeRows(ids);
roomDb.endTransaction();
insertRows(ids);
如果我中间休息一下也没关系:
It's also fine if I give a sleep in-between instead:
removeRows(ids);
Thread.sleep(500);
insertRows(ids);
Room 的文档似乎并不多,我想知道当我要完成顺序操作时是否应该像上面那样使用事务块,或者有没有更好的方法.
There doesn't seem to be much documentation for Room, and was wondering if I should use the transaction block like the above when I have sequential operations to be done, or is there any better way of doing it.
EDIT:@CommonsWare 指出后,@Query
是异步的,而 @Insert
和 @Delete
是同步的.鉴于此,我将如何获得将行删除为异步的查询:
EDIT: After @CommonsWare pointed out, @Query
are asynchronous, while @Insert
and @Delete
are synchronous. In view of this, how would I get a query which deletes rows to be async:
@Query("DELETE from table WHERE id IN(:ids)")
int removeRows(List<Long> ids);
根据构建输出,如果我尝试将返回类型包装在 Flowable
中,我得到 删除方法必须返回 void 或返回 int(已删除的行数)
代码>.
According to the build output I get Deletion methods must either return void or return int (the number of deleted rows)
, if I try to wrap the return type in a Flowable
.
推荐答案
正如在 交易,您可以执行以下操作:
As pointed out on documentation for Transaction, you can do following:
@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);
}
}
这篇关于Android Room 数据库事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!