Android Room - 使用自动生成获取新插入行的ID

Dev*_*cie 104 android persistent-storage android-room

这是我使用Room Persistence Library将数据插入数据库的方法:

实体:

@Entity
class User {
    @PrimaryKey(autoGenerate = true)
    public int id;
    //...
}
Run Code Online (Sandbox Code Playgroud)

数据访问对象:

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

在上述方法本身完成插入后,是否可以返回User的id而无需编写单独的select查询?

Mat*_*Pag 145

基于此处的文档(在代码片段下方)

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

  • long 用于单次插入操作
  • long[]Long[]List<Long>多个INSERT操作
  • void 如果你不关心插入的id

  • 在SQLite中,您可以拥有的最大主键ID是64位有符号整数,因此最大值为9,223,372,036,854,775,807(仅为正,因为它是一个id).在java中,int是32位有符号数,并且最大正值是2,147,483,647,因此无法表示所有id.您需要使用Java long,其最大值为9,223,372,036,854,775,807来表示所有ID.文档仅作为示例,但api的设计考虑到了这一点(这就是为什么它返回long而不是int或double) (8认同)
  • 为什么在文档中对id类型说int但返回long?是否假设ID永远不会足够长?所以行ID和自动生成ID实际上是一回事吗? (3认同)
  • 没错,但是即使在最坏的情况下,Room的API也应该可以使用,并且必须遵循SQlite的规范。在这种情况下,长时间使用int实际上是相同的事情,额外的内存消耗可以忽略不计 (3认同)
  • 好的,所以它真的应该很长。但也许在大多数情况下,sqlite 数据库中不会有 90 亿行,因此他们使用 int 作为 userId 的示例,因为它占用的内存较少(或者这是一个错误)。这就是我从中得到的。感谢您解释为什么它返回很长时间。 (2认同)
  • 忽略我的最后一条评论 - sqlite 文档说“rowid 表的主键(如果有的话)通常不是表的真正主键,从某种意义上说,它不是底层 B- 使用的唯一键树存储引擎。此规则的例外是当 rowid 表声明 INTEGER PRIMARY KEY 时。在例外情况下,INTEGER PRIMARY KEY 成为 rowid 的别名。” (https://www.sqlite.org/rowidtable.html )因此,如果您有一个 kotlin/java Long 主键,那么它应该始终与 Dao 查询返回的 rowId 相同。 (2认同)

Qua*_*yen 17

@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);
Run Code Online (Sandbox Code Playgroud)

  • `return Single.fromCallable(() - > dbService.YourDao().insert(mObject));` (3认同)

Har*_*ian 8

通过以下代码段获取行 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;
 }
Run Code Online (Sandbox Code Playgroud)

参考:Java Executor Service Tutorial了解更多关于 Callable 的信息。


Cuo*_* Vo 6

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

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

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

并使用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.

        }
    });
Run Code Online (Sandbox Code Playgroud)

  • *“如果您的语句成功,则插入一条记录的返回值为1”* -&gt; 根据此文档:https://developer.android.com/training/data-storage/room/accessing-data“如果@Insert 方法只接收 1 个参数,它可以返回一个 long,**这是插入项的新 rowId。** 如果参数是数组或集合,则应 **return long[] 或 List&lt;长&gt;**代替。” (2认同)

小智 6

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

 @Insert(onConflict = OnConflictStrategy.REPLACE)
 fun insert(recipes: CookingRecipes): Long
Run Code Online (Sandbox Code Playgroud)

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

fun addRecipesData(cookingRecipes: CookingRecipes): Single<Long>? {
        return Single.fromCallable<Long> { recipesDao.insertManual(cookingRecipes) }
}
Run Code Online (Sandbox Code Playgroud)

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


And*_*oob 6

根据用@Insert 注释的文档函数可以返回rowId。

如果@Insert 方法只接收 1 个参数,它可以返回一个 long,即插入项的新 rowId。如果参数是数组或集合,则应改为返回 long[] 或 List<Long>。

我遇到的问题是它返回的是 rowId 而不是 id,我仍然没有找到如何使用 rowId 获取 id。

编辑:我现在知道如何从 rowId 获取 id。这是 SQL 命令:

SELECT id FROM table_name WHERE rowid = :rowId
Run Code Online (Sandbox Code Playgroud)


kga*_*oid 5

经过一番挣扎,我设法解决了这个问题。这是我使用MMVM 架构的解决方案

学生.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
}
Run Code Online (Sandbox Code Playgroud)

StudentDao.kt

interface StudentDao {
    @Insert
    fun insertStudent(student: Student) : Long
}
Run Code Online (Sandbox Code Playgroud)

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 }
                }
    }
}
Run Code Online (Sandbox Code Playgroud)

学生视图模型.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)
                    }

                })
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

在片段中:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用过 DataBinding。这是我的 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>
Run Code Online (Sandbox Code Playgroud)

我一直在努力使用 asynctask 来实现这一点,因为房间插入和删除操作必须在单独的线程中完成。终于能够使用 RxJava 中的Single类型 observable来做到这一点。

这是 rxjava 的 Gradle 依赖项:

implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.0.3' 
Run Code Online (Sandbox Code Playgroud)