这是我如何使用房间持久性库插入数据到数据库:
实体:
@Entity
class User {
@PrimaryKey(autoGenerate = true)
public int id;
//...
}
数据访问对象:
@Dao
public interface UserDao{
@Insert(onConflict = IGNORE)
void insertUser(User user);
//...
}
是否有可能返回用户的id一旦插入完成在上面的方法本身,而不编写一个单独的选择查询?
在你的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
根据文档中标注了@Insert的函数可以返回rowId。
如果@Insert方法只接收到1个参数,它可以返回一个long,即插入项的新rowId。如果参数是数组或集合,则应该返回long[]或List< long >。
我有这个问题是,它返回rowId而不是id,我仍然没有找到如何使用rowId获得id。
编辑:我现在知道如何从rowId获取id。下面是SQL命令:
SELECT id FROM table_name WHERE rowid = :rowId