问题
This is how I am inserting data into database using Room Persistence Library:
Entity:
@Entity
class User {
@PrimaryKey(autoGenerate = true)
public int id;
//...
}
Data access object:
@Dao
public interface UserDao{
@Insert(onConflict = IGNORE)
void insertUser(User user);
//...
}
Is it possible to return the id of User once the insertion is completed in the above method itself without writing a separate select query?
回答1:
Based on the documentation here (below the code snippet)
A method annotated with the @Insert
annotation can return:
long
for single insert operationlong[]
orLong[]
orList<Long>
for multiple insert operationsvoid
if you don't care about the inserted id(s)
回答2:
@Insert
function can return void
, long
, long[]
or List<Long>
. Please try this.
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insert(User user);
// Insert multiple items
@Insert(onConflict = OnConflictStrategy.REPLACE)
long[] insert(User... user);
回答3:
The return value of the insertion for one record will be 1 if your statement successfully.
In case you want to insert list of objects, you can go with:
@Insert(onConflict = OnConflictStrategy.REPLACE)
public long[] addAll(List<Object> list);
And execute it with 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.
}
});
回答4:
Get the row ID by the following sniplet. It uses callable on an ExecutorService with Future.
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;
}
Ref: Java Executor Service Tutorial for more information on Callable.
回答5:
In you Dao, the query insert return Long i.e. the rowId inserted.
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(recipes: CookingRecipes): Long
In your Model(Repository) class : (MVVM)
fun addRecipesData(cookingRecipes: CookingRecipes): Single<Long>? {
return Single.fromCallable<Long> { recipesDao.insertManual(cookingRecipes) }
}
In your ModelView class: (MVVM) Handle LiveData with DisposableSingleObserver.
Working sourcer reference : https://github.com/SupriyaNaveen/CookingRecipes
来源:https://stackoverflow.com/questions/44364240/android-room-get-the-id-of-new-inserted-row-with-auto-generate