问题
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