插入房间后的 Rowid
Rowid after Insert in Room
当主键是自动生成的字段时,我不确定使用 Android 的 Room Persistence Library 插入返回的值。
假设您有一个这样的房间实体:
@Entity()
public class Message {
@PrimaryKey(autoGenerate = true)
public long id;
public String text;
}
还有一个像这样的 Dao 接口:
@Dao
public interface MessageDao {
@Insert
long insert(Message messages);
@Update
void update(Message... messages);
}
我创建了一个 Message 实例,然后像这样持久化它:
Message message = new Message();
message.text = "Hello!"
long rowId = AppDatabase.getInstance(context).messageDao().insert(message);
insert() 返回的 rowid 值是否始终等于 Room 分配给主键字段的值 "id",或者它们可以不同?
换句话说,"id"字段是底层SQLite的rowid列的别名吗table?
如果它们是别名,我可以将 rowid 值存储在我的 "id" 字段中,以供将来使用(例如更新),这样:
message.id = rowId;
message.text = "Goodbye!"
AppDatabase.getInstance(context).messageDao().update(message);
如果他们不是别名,我该怎么做?
正如 documentation (unfortunately not in the @Insert 文档)所说:
If the @Insert method receives only 1 parameter, it can return a long,
which is the new rowId for the inserted item. If the parameter is
an array or a collection, it should return long[] or List
instead.
要了解什么是 rowId,请遵循此 link:https://www.sqlite.org/rowidtable.html
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 在你的情况下是你的主键的别名。是的,您可以存储它以备将来使用。
当主键是自动生成的字段时,我不确定使用 Android 的 Room Persistence Library 插入返回的值。
假设您有一个这样的房间实体:
@Entity()
public class Message {
@PrimaryKey(autoGenerate = true)
public long id;
public String text;
}
还有一个像这样的 Dao 接口:
@Dao
public interface MessageDao {
@Insert
long insert(Message messages);
@Update
void update(Message... messages);
}
我创建了一个 Message 实例,然后像这样持久化它:
Message message = new Message();
message.text = "Hello!"
long rowId = AppDatabase.getInstance(context).messageDao().insert(message);
insert() 返回的 rowid 值是否始终等于 Room 分配给主键字段的值 "id",或者它们可以不同?
换句话说,"id"字段是底层SQLite的rowid列的别名吗table?
如果它们是别名,我可以将 rowid 值存储在我的 "id" 字段中,以供将来使用(例如更新),这样:
message.id = rowId;
message.text = "Goodbye!"
AppDatabase.getInstance(context).messageDao().update(message);
如果他们不是别名,我该怎么做?
正如 documentation (unfortunately not in the @Insert 文档)所说:
If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long[] or List instead.
要了解什么是 rowId,请遵循此 link:https://www.sqlite.org/rowidtable.html
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 在你的情况下是你的主键的别名。是的,您可以存储它以备将来使用。