Room API - 如何检索最近插入的实体生成的 id?

tal*_*a06 3 sqlite android android-sqlite android-room

我需要检索id最近插入的实体的生成值,如下面添加的代码示例所示:

如上所述,id实体的字段用Student注释PrimaryKey(autoGenerate= true)

Student s = new Student();
s.setName("foo");
// call of other setters
appDatabase.getGenericDAO().insertStudent(s);
// Now I need to retrieve the value of generated id as we do in Hibernate by the usage of merge method
Integer id = s.getId(); 
Run Code Online (Sandbox Code Playgroud)

@Dao
public interface IGenericDAO {

    @Insert
    Long insertStudent(Student student);

    @Insert
    void insertOgrenci(List<Student> studentList);

    @Update
    void updateOgrenci(Ogrenci... ogrenci);

    @Delete
    void deleteOgrenci(Ogrenci... ogrenci); 

}
Run Code Online (Sandbox Code Playgroud)

Com*_*are 7

让你的@Insert方法返回一个long

@Insert
long insertStudent(Student s);
Run Code Online (Sandbox Code Playgroud)

返回值将是rowId行的 ,这应该是自动生成的主键值。