Android Room - 获取自动生成的新插入行的 ID
Android Room - Get the id of new inserted row with auto-generate
这就是我使用 Room Persistence Library 将数据插入数据库的方式:
实体:
@Entity
class User {
@PrimaryKey(autoGenerate = true)
public int id;
//...
}
数据访问对象:
@Dao
public interface UserDao{
@Insert(onConflict = IGNORE)
void insertUser(User user);
//...
}
是否可以在上述方法本身完成插入后 return User 的 id 而无需编写单独的 select 查询?
@Insert
函数可以 return void
、long
、long[]
或 List<Long>
。请试试这个。
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insert(User user);
// Insert multiple items
@Insert(onConflict = OnConflictStrategy.REPLACE)
long[] insert(User... user);
基于文档here(代码段下方)
使用@Insert
注解的方法可以return:
long
for single insert operation
long[]
or Long[]
or List<Long>
for multiple insert operations
void
if you don't care about the inserted id(s)
插入一条记录的return值为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.
}
});
在您的 Dao 中,插入查询 returns Long
即插入的 rowId。
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(recipes: CookingRecipes): Long
在您的模型(存储库)中 class : (MVVM)
fun addRecipesData(cookingRecipes: CookingRecipes): Single<Long>? {
return Single.fromCallable<Long> { recipesDao.insertManual(cookingRecipes) }
}
在您的 ModelView 中 class:(MVVM) 使用 DisposableSingleObserver 处理 LiveData。
工作来源参考:https://github.com/SupriyaNaveen/CookingRecipes
通过以下代码获取行 ID。它在带有 Future 的 ExecutorService 上使用可调用。
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 的更多信息。
经过一番努力,我设法解决了这个问题。这是我使用 MMVM 架构的解决方案:
Student.kt
@Entity(tableName = "students")
data class Student(
@NotNull var name: String,
@NotNull var password: String,
var subject: String,
var email: String
) {
@PrimaryKey(autoGenerate = true)
var roll: Int = 0
}
StudentDao.kt
interface StudentDao {
@Insert
fun insertStudent(student: Student) : Long
}
StudentRepository.kt
class StudentRepository private constructor(private val studentDao: StudentDao)
{
fun getStudents() = studentDao.getStudents()
fun insertStudent(student: Student): Single<Long>? {
return Single.fromCallable(
Callable<Long> { studentDao.insertStudent(student) }
)
}
companion object {
// For Singleton instantiation
@Volatile private var instance: StudentRepository? = null
fun getInstance(studentDao: StudentDao) =
instance ?: synchronized(this) {
instance ?: StudentRepository(studentDao).also { instance = it }
}
}
}
StudentViewModel.kt
class StudentViewModel (application: Application) : AndroidViewModel(application) {
var status = MutableLiveData<Boolean?>()
private var repository: StudentRepository = StudentRepository.getInstance( AppDatabase.getInstance(application).studentDao())
private val disposable = CompositeDisposable()
fun insertStudent(student: Student) {
disposable.add(
repository.insertStudent(student)
?.subscribeOn(Schedulers.newThread())
?.observeOn(AndroidSchedulers.mainThread())
?.subscribeWith(object : DisposableSingleObserver<Long>() {
override fun onSuccess(newReturnId: Long?) {
Log.d("ViewModel Insert", newReturnId.toString())
status.postValue(true)
}
override fun onError(e: Throwable?) {
status.postValue(false)
}
})
)
}
}
片段中:
class RegistrationFragment : Fragment() {
private lateinit var dataBinding : FragmentRegistrationBinding
private val viewModel: StudentViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initialiseStudent()
viewModel.status.observe(viewLifecycleOwner, Observer { status ->
status?.let {
if(it){
Toast.makeText(context , "Data Inserted Sucessfully" , Toast.LENGTH_LONG).show()
val action = RegistrationFragmentDirections.actionRegistrationFragmentToLoginFragment()
Navigation.findNavController(view).navigate(action)
} else
Toast.makeText(context , "Something went wrong" , Toast.LENGTH_LONG).show()
//Reset status value at first to prevent multitriggering
//and to be available to trigger action again
viewModel.status.value = null
//Display Toast or snackbar
}
})
}
fun initialiseStudent() {
var student = Student(name =dataBinding.edName.text.toString(),
password= dataBinding.edPassword.text.toString(),
subject = "",
email = dataBinding.edEmail.text.toString())
dataBinding.viewmodel = viewModel
dataBinding.student = student
}
}
我用过DataBinding.Here是我的XML:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="student"
type="com.kgandroid.studentsubject.data.Student" />
<variable
name="listener"
type="com.kgandroid.studentsubject.view.RegistrationClickListener" />
<variable
name="viewmodel"
type="com.kgandroid.studentsubject.viewmodel.StudentViewModel" />
</data>
<androidx.core.widget.NestedScrollView
android:id="@+id/nestedScrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
tools:context="com.kgandroid.studentsubject.view.RegistrationFragment">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/constarintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:isScrollContainer="true">
<TextView
android:id="@+id/tvRoll"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:gravity="center_horizontal"
android:text="Roll : 1"
android:textColor="@color/colorPrimary"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/edName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvRoll" />
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:text="Name:"
android:textColor="@color/colorPrimary"
android:textSize="18sp"
app:layout_constraintBaseline_toBaselineOf="@+id/edName"
app:layout_constraintEnd_toStartOf="@+id/edName"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/tvEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:textColor="@color/colorPrimary"
android:textSize="18sp"
app:layout_constraintBaseline_toBaselineOf="@+id/edEmail"
app:layout_constraintEnd_toStartOf="@+id/edEmail"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="@+id/edEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edName" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:textColor="@color/colorPrimary"
android:textSize="18sp"
app:layout_constraintBaseline_toBaselineOf="@+id/edPassword"
app:layout_constraintEnd_toStartOf="@+id/edPassword"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="@+id/edPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edEmail" />
<Button
android:id="@+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="32dp"
android:background="@color/colorPrimary"
android:text="REGISTER"
android:onClick="@{() -> viewmodel.insertStudent(student)}"
android:textColor="@android:color/background_light"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edPassword" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
</layout>
我为使用 asynctask 完成此任务付出了很多努力,因为房间插入和删除操作必须在单独的线程中完成。终于可以用 Single 做到这一点
在 RxJava 中输入 observable。
这里是 Gradle rxjava 的依赖项:
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.0.3'
根据用@Insert 注释的documentation 函数可以return rowId。
If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long[] or List<Long> instead.
我遇到的问题是它 return 是 rowId 而不是 id,我仍然没有找到如何使用 rowId 获取 id。
编辑:我现在知道如何从 rowId 中获取 ID。这是 SQL 命令:
SELECT id FROM table_name WHERE rowid = :rowId
如果@Insert 方法接收单个参数,它可以return 一个long 值,它是插入项的新rowId。
enter link description here
@Insert
suspend fun insert(myEntity: MyEntity):Long
这就是我使用 Room Persistence Library 将数据插入数据库的方式:
实体:
@Entity
class User {
@PrimaryKey(autoGenerate = true)
public int id;
//...
}
数据访问对象:
@Dao
public interface UserDao{
@Insert(onConflict = IGNORE)
void insertUser(User user);
//...
}
是否可以在上述方法本身完成插入后 return User 的 id 而无需编写单独的 select 查询?
@Insert
函数可以 return void
、long
、long[]
或 List<Long>
。请试试这个。
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insert(User user);
// Insert multiple items
@Insert(onConflict = OnConflictStrategy.REPLACE)
long[] insert(User... user);
基于文档here(代码段下方)
使用@Insert
注解的方法可以return:
long
for single insert operationlong[]
orLong[]
orList<Long>
for multiple insert operationsvoid
if you don't care about the inserted id(s)
插入一条记录的return值为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.
}
});
在您的 Dao 中,插入查询 returns Long
即插入的 rowId。
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(recipes: CookingRecipes): Long
在您的模型(存储库)中 class : (MVVM)
fun addRecipesData(cookingRecipes: CookingRecipes): Single<Long>? {
return Single.fromCallable<Long> { recipesDao.insertManual(cookingRecipes) }
}
在您的 ModelView 中 class:(MVVM) 使用 DisposableSingleObserver 处理 LiveData。
工作来源参考:https://github.com/SupriyaNaveen/CookingRecipes
通过以下代码获取行 ID。它在带有 Future 的 ExecutorService 上使用可调用。
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 的更多信息。
经过一番努力,我设法解决了这个问题。这是我使用 MMVM 架构的解决方案:
Student.kt
@Entity(tableName = "students")
data class Student(
@NotNull var name: String,
@NotNull var password: String,
var subject: String,
var email: String
) {
@PrimaryKey(autoGenerate = true)
var roll: Int = 0
}
StudentDao.kt
interface StudentDao {
@Insert
fun insertStudent(student: Student) : Long
}
StudentRepository.kt
class StudentRepository private constructor(private val studentDao: StudentDao)
{
fun getStudents() = studentDao.getStudents()
fun insertStudent(student: Student): Single<Long>? {
return Single.fromCallable(
Callable<Long> { studentDao.insertStudent(student) }
)
}
companion object {
// For Singleton instantiation
@Volatile private var instance: StudentRepository? = null
fun getInstance(studentDao: StudentDao) =
instance ?: synchronized(this) {
instance ?: StudentRepository(studentDao).also { instance = it }
}
}
}
StudentViewModel.kt
class StudentViewModel (application: Application) : AndroidViewModel(application) {
var status = MutableLiveData<Boolean?>()
private var repository: StudentRepository = StudentRepository.getInstance( AppDatabase.getInstance(application).studentDao())
private val disposable = CompositeDisposable()
fun insertStudent(student: Student) {
disposable.add(
repository.insertStudent(student)
?.subscribeOn(Schedulers.newThread())
?.observeOn(AndroidSchedulers.mainThread())
?.subscribeWith(object : DisposableSingleObserver<Long>() {
override fun onSuccess(newReturnId: Long?) {
Log.d("ViewModel Insert", newReturnId.toString())
status.postValue(true)
}
override fun onError(e: Throwable?) {
status.postValue(false)
}
})
)
}
}
片段中:
class RegistrationFragment : Fragment() {
private lateinit var dataBinding : FragmentRegistrationBinding
private val viewModel: StudentViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initialiseStudent()
viewModel.status.observe(viewLifecycleOwner, Observer { status ->
status?.let {
if(it){
Toast.makeText(context , "Data Inserted Sucessfully" , Toast.LENGTH_LONG).show()
val action = RegistrationFragmentDirections.actionRegistrationFragmentToLoginFragment()
Navigation.findNavController(view).navigate(action)
} else
Toast.makeText(context , "Something went wrong" , Toast.LENGTH_LONG).show()
//Reset status value at first to prevent multitriggering
//and to be available to trigger action again
viewModel.status.value = null
//Display Toast or snackbar
}
})
}
fun initialiseStudent() {
var student = Student(name =dataBinding.edName.text.toString(),
password= dataBinding.edPassword.text.toString(),
subject = "",
email = dataBinding.edEmail.text.toString())
dataBinding.viewmodel = viewModel
dataBinding.student = student
}
}
我用过DataBinding.Here是我的XML:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="student"
type="com.kgandroid.studentsubject.data.Student" />
<variable
name="listener"
type="com.kgandroid.studentsubject.view.RegistrationClickListener" />
<variable
name="viewmodel"
type="com.kgandroid.studentsubject.viewmodel.StudentViewModel" />
</data>
<androidx.core.widget.NestedScrollView
android:id="@+id/nestedScrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
tools:context="com.kgandroid.studentsubject.view.RegistrationFragment">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/constarintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:isScrollContainer="true">
<TextView
android:id="@+id/tvRoll"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:gravity="center_horizontal"
android:text="Roll : 1"
android:textColor="@color/colorPrimary"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/edName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvRoll" />
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:text="Name:"
android:textColor="@color/colorPrimary"
android:textSize="18sp"
app:layout_constraintBaseline_toBaselineOf="@+id/edName"
app:layout_constraintEnd_toStartOf="@+id/edName"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/tvEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:textColor="@color/colorPrimary"
android:textSize="18sp"
app:layout_constraintBaseline_toBaselineOf="@+id/edEmail"
app:layout_constraintEnd_toStartOf="@+id/edEmail"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="@+id/edEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edName" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:textColor="@color/colorPrimary"
android:textSize="18sp"
app:layout_constraintBaseline_toBaselineOf="@+id/edPassword"
app:layout_constraintEnd_toStartOf="@+id/edPassword"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="@+id/edPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edEmail" />
<Button
android:id="@+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="32dp"
android:background="@color/colorPrimary"
android:text="REGISTER"
android:onClick="@{() -> viewmodel.insertStudent(student)}"
android:textColor="@android:color/background_light"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edPassword" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
</layout>
我为使用 asynctask 完成此任务付出了很多努力,因为房间插入和删除操作必须在单独的线程中完成。终于可以用 Single 做到这一点 在 RxJava 中输入 observable。
这里是 Gradle rxjava 的依赖项:
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.0.3'
根据用@Insert 注释的documentation 函数可以return rowId。
If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long[] or List<Long> instead.
我遇到的问题是它 return 是 rowId 而不是 id,我仍然没有找到如何使用 rowId 获取 id。
编辑:我现在知道如何从 rowId 中获取 ID。这是 SQL 命令:
SELECT id FROM table_name WHERE rowid = :rowId
如果@Insert 方法接收单个参数,它可以return 一个long 值,它是插入项的新rowId。 enter link description here
@Insert
suspend fun insert(myEntity: MyEntity):Long