这是我如何使用房间持久性库插入数据到数据库:

实体:

@Entity
class User {
    @PrimaryKey(autoGenerate = true)
    public int id;
    //...
}

数据访问对象:

@Dao
public interface UserDao{
    @Insert(onConflict = IGNORE)
    void insertUser(User user);
    //...
}

是否有可能返回用户的id一旦插入完成在上面的方法本身,而不编写一个单独的选择查询?


当前回答

如果语句成功,一条记录的插入返回值将为1。

如果你想插入对象列表,你可以使用:

@Insert(onConflict = OnConflictStrategy.REPLACE)
public long[] addAll(List<Object> list);

然后用Rx2执行:

Observable.fromCallable(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            return yourDao.addAll(list<Object>);
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Object>() {
        @Override
        public void accept(@NonNull Object o) throws Exception {
           // the o will be Long[].size => numbers of inserted records.

        }
    });

其他回答

如果@Insert方法接收到单个参数,它可以返回一个长值,即插入项的新rowId。 在这里输入链接描述

@Insert
suspend fun insert(myEntity: MyEntity):Long

如果语句成功,一条记录的插入返回值将为1。

如果你想插入对象列表,你可以使用:

@Insert(onConflict = OnConflictStrategy.REPLACE)
public long[] addAll(List<Object> list);

然后用Rx2执行:

Observable.fromCallable(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            return yourDao.addAll(list<Object>);
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Object>() {
        @Override
        public void accept(@NonNull Object o) throws Exception {
           // the o will be Long[].size => numbers of inserted records.

        }
    });

根据下面的文档(代码片段下面)

使用@Insert注释的方法可以返回:

长单次插入操作 long[]或long[]或List< long >用于多个插入操作 如果你不关心插入的id,则为空

通过下面的复选框获取行ID。它在带有Future的ExecutorService上使用callable。

 private UserDao userDao;
 private ExecutorService executorService;

 public long insertUploadStatus(User user) {
    Callable<Long> insertCallable = () -> userDao.insert(user);
    long rowId = 0;

    Future<Long> future = executorService.submit(insertCallable);
     try {
         rowId = future.get();
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    return rowId;
 }

参考:关于可调用的更多信息,Java Executor服务教程。

在你的Dao中,插入查询返回Long,即插入的rowId。

 @Insert(onConflict = OnConflictStrategy.REPLACE)
 fun insert(recipes: CookingRecipes): Long

在你的模型(存储库)类中:(MVVM)

fun addRecipesData(cookingRecipes: CookingRecipes): Single<Long>? {
        return Single.fromCallable<Long> { recipesDao.insertManual(cookingRecipes) }
}

在你的ModelView类中:(MVVM)用DisposableSingleObserver处理LiveData。 工作源代码参考:https://github.com/SupriyaNaveen/CookingRecipes