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

依然范特西╮ 提交于 2019-12-13 20:37:31

问题


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

}

回答1:


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.



来源:https://stackoverflow.com/questions/49950254/room-api-how-to-retrieve-recently-inserted-generated-id-of-the-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!