【问题标题】:Room API - How to retrieve recently inserted generated id of the entity?Room API - 如何检索最近插入的实体生成 id?
【发布时间】:2018-04-20 21:57:24
【问题描述】:

我需要检索最近插入的实体的生成 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
public interface IGenericDAO {

    @Insert
    Long insertStudent(Student student);

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

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

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

}

【问题讨论】:

    标签: android sqlite android-sqlite android-room


    【解决方案1】:

    让您的@Insert 方法返回long

    @Insert
    long insertStudent(Student s);
    

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

    【讨论】:

    • @talha06:那么……有什么问题?
    • @GkMohammadEmon:不,您可以定义自己的主键。但是,无论您是否将其用作主键,SQLite 都会添加唯一的行 ID。
    • @GkMohammadEmon:IIRC,是的。自动生成的主键应该是行 ID,并且是单个实体 insert() 将返回的内容。
    • @CommonsWare 是否保证自动生成的主键、rowid 和插入返回的值相同?我在文档中没有看到。
    • @JulianSymes:AFAIK,insert() 返回 SQLite 公开的值 via sqlite3_last_insert_rowid()。引用这些文档,“大多数 SQLite 表(除了 WITHOUT ROWID 表)中的每个条目都有一个唯一的 64 位有符号整数键,称为“rowid”。rowid 始终可用作名为 ROWID、OID 或 ROWID 只要这些名称也没有被显式声明的列使用。如果表有一个 INTEGER PRIMARY KEY 类型的列,那么该列是 rowid 的另一个别名。"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 2011-07-09
    • 1970-01-01
    • 2011-07-30
    • 2019-01-09
    • 2017-11-23
    相关资源
    最近更新 更多