简体   繁体   中英

Room API - How to retrieve recently inserted generated id of the entity?

I need to retrieve the generated id value of an entity which is recently inserted as the code sample added below demonstrates:

As mentioned above, the id field of the entity Student is annotated with 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(); 

DAO

@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); 

}

Have your @Insert method return a long :

@Insert
long insertStudent(Student s);

The return value will be the rowId of the row, and that should be the auto-generated primary key value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM