Android Room数据库交易 [英] Android Room database transactions
问题描述
使用Android中新的Room数据库时,我需要在其中需要执行两个顺序的操作:
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.
编辑:@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
中,则会得到Deletion methods must either return void or return int (the number of deleted rows)
.
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屋!