插入房间后的Rowid [英] Rowid after Insert in Room

查看:124
本文介绍了插入房间后的Rowid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当主键是自动生成的字段时,我不确定使用Android的Room Persistence库通过插入返回的值.

I'm not sure about the value returned by an insert using the Room Persistence Library for Android, when the primary key is an autogenerated field.

假设您有一个这样的房间实体:

Say you have a Room Entity like this:

@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实例,然后像这样持久保存它:

I create a Message instance, and then I persist it like this:

Message message = new Message();
message.text = "Hello!"
long rowId = AppDatabase.getInstance(context).messageDao().insert(message);

insert()返回的rowid值是否始终等于Room分配给主键字段"id"的值,或者它们可以不同?

Is the rowid value returned by the insert() always equal to the value assigned by Room to the primary key field "id", or they can differ?

换句话说,"id"字段是否是基础SQLite表的rowid列的别名?

In other words, is the "id" field an alias for the rowid column of the underlying SQLite table or not?

如果它们是别名,我可以通过以下方式将rowid值存储在我的"id"字段中,以备将来使用(例如,用于更新):

If they would be alias, I could store the rowid value in my "id" field, for future use (e.g. for update), this way:

message.id = rowId;
message.text = "Goodbye!"
AppDatabase.getInstance(context).messageDao().update(message);

如果它们不是别名,我该怎么办?

If they are not alias, how can I do that?

推荐答案

作为 @Insert 文档)说:

As the documentation (unfortunately not in the @Insert documentation) say:

如果 @Insert 方法仅接收一个参数,可以返回很长的时间 这是插入项目的新 rowId .如果参数是 数组或集合,它应该返回long []或List 代替.

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: https://www.sqlite.org/rowidtable. html

To understand what rowId is fallow this link: https://www.sqlite.org/rowidtable.html

rowid表的PRIMARY KEY(如果有)通常不是 表的真正主键,因为它不是唯一的 基础B树存储引擎使用的密钥.的例外 该规则是在rowid表声明一个INTEGER PRIMARY KEY时.在 唯一的例外是INTEGER PRIMARY KEY成为rowid的别名.

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是主键的别名.是的,您可以将其存储以备将来使用.

So... yes. rowid in your case IS an alias of your primary key. And YES you can store it for future use.

这篇关于插入房间后的Rowid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆