对于android房间界面,我想获取自动生成的id(作为刚刚插入的记录的主键),这样我就可以把它放在对象中而不用在插入后执行select,select可能会返回错误如果这些记录类型没有其他唯一属性或属性集,则记录。
例如,将两个同名的人插入到同一个表中。你可能会说生成一个复合键来制作一个唯一的集合。但是,这可能涉及添加本来不需要的新字段。
我看过各种链接,包括下面的链接。有人提到,如果声明插入方法返回整数(或长整数)并成功,则返回的是行标识。 但是,据我了解,不能假定行 ID 与主键相同。 (引用 Rowid after Insert in Room)。 我无法评论任何帖子,因为我没有足够的声望点数。 我很感激任何关于什么可能是解决这个问题的好/典型方法的评论。
这些是我看过的帖子:
Android Room - Get the id of new inserted row with auto-generate
https://developer.android.com/training/data-storage/room/accessing-data https://commonsware.com/AndroidArch/previews/the-dao-of-entities
最佳答案
只为将来看到此问题的任何人延迟回答
来自 SQLite docs 它说:
The PRIMARY KEY of a rowid table (if there is one) is usually not the true primary key for the table, in the sense that it is not the unique key used by the underlying B-tree storage engine. The exception to this rule is when the rowid table declares an INTEGER PRIMARY KEY. In the exception, the INTEGER PRIMARY KEY becomes an alias for the rowid.
因此,假设插入查询返回的 rowId 与 autoincremented-primary-key
相同是正确的https://stackoverflow.com/questions/54168315/