android - 在 Room ORM 中批量插入或更新

标签 android android-room

我正在尝试使用 android room ORM。许多 ORM 都有这种方法 insertOrUpdate 方法。我如何实现这一目标?我想在单个事务中插入或更新多行,即,如果存在行则更新它,否则插入一个新条目。

最佳答案

您可以使用 conflict resolution set to replace 进行插入:

@Dao
public interface MyDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    public void insertUsers(User... users);
}

请注意(来自 Room documentation ):

Note: SQLite handles @Insert(onConflict = REPLACE) as a set of REMOVE and REPLACE operations instead of a single UPDATE operation. This method of replacing conflicting values could affect your foreign key constraints. For more details, see the SQLite documentation for the ON_CONFLICT clause.

在 Room 中,这个单一的插入语句在一个事务中运行,所以它在大多数时候应该是安全的。

或者,您可以在事务中运行语句:

myDb.runInTransaction(new Runnable() {
     @Override
     public void run() {
         // Your operations
     }
});

或者,来自另一个 StackOverflow answer :

@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 ORM 中批量插入或更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48125364/

相关文章:

android - 为 android 列表预捕获图像的最佳做法是什么?

android - 我正在为盲人开发一个应用程序,所以我需要阅读按钮输入

java - 在json文件中将图像转换为Base64问题

android - 如何清除 ListView 上的项目选择

Android:这条警告消息指的是什么? -(网络核心)

android - 房间错误 : The columns returned by the query does not have the fields fieldname

java - 插入 Room Persistence Library Android Studio 后获取 RowID

android - 如何使用过多的 Completable 方法执行顺序操作

android - 将 androidx.room 打包到 aar 库中的项目导致 java.lang.NoClassDefFoundError : Failed resolution of: Landroidx/room/RoomDatabase

android - ViewModel中的LiveData类型不匹配