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

3

我需要获取最近插入的实体的生成id值,如下所示的代码示例:

如上所述,实体Studentid字段带有注释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个回答

9

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

@Insert
long insertStudent(Student s);

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

1
@GkMohammadEmon:不,你可以定义自己的主键。但是,不管您是否将其用作主键,SQLite始终会添加唯一的行ID。 - CommonsWare
那么,如果我想获取最新插入值的主键,最好的方法是什么?@CommonsWare - Gk Mohammad Emon
1
@GkMohammadEmon:如果我没记错的话,是的。自动生成的主键应该是行ID,并且是单个实体insert()返回的内容。 - CommonsWare
1
@CommonsWare 这个自动生成的主键,rowid和插入返回的值是否保证是相同的?我在文档中没有看到过这样的说明。 - JulianSymes
1
据我所知,insert()返回SQLite通过sqlite3_last_insert_rowid()公开的值。引用这些文档,“大多数SQLite表中的每个条目(除了WITHOUT ROWID表)都有一个名为“rowid”的唯一64位有符号整数键。只要这些名称没有被显式声明的列使用,ROWID、OID或_ROWID_作为未声明的列名始终可用。如果表具有INTEGER PRIMARY KEY类型的列,则该列是rowid的另一个别名。” - CommonsWare
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接