这是我使用Room Persistence Library将数据插入数据库的方法:
实体:
@Entity
class User {
@PrimaryKey(autoGenerate = true)
public int id;
//...
}
数据访问对象:
@Dao
public interface UserDao{
@Insert(onConflict = IGNORE)
void insertUser(User user);
//...
}
在上述方法本身完成插入后,是否可以返回User的id而无需编写单独的select查询?
基于文档here(在代码片段下方)
使用@Insert
注释注释的方法可以返回:
long
用于单次插入操作long[]
或Long[]
或List<Long>
用于多次插入操作- 如果你不关心插入的id,
void
@Insert
函数可以返回void
,long
,long[]
或List<Long>
。请试试这个。
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insert(User user);
// Insert multiple items
@Insert(onConflict = OnConflictStrategy.REPLACE)
long[] insert(User... user);
如果您的语句成功,则一条记录的插入返回值将为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.
}
});
通过以下代码获取行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 Service Tutorial有关Callable的更多信息。
在你Dao中,查询插入返回Long,即插入的rowId。
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(recipes: CookingRecipes): Long
在您的Model(Repository)类中:(MVVM)
fun addRecipesData(cookingRecipes: CookingRecipes): Single<Long>? {
return Single.fromCallable<Long> { recipesDao.insertManual(cookingRecipes) }
}
在ModelView类中:(MVVM)使用DisposableSingleObserver处理LiveData。 工作来源参考:https://github.com/SupriyaNaveen/CookingRecipes